函数不能在$(document).ready(function(){中调用

时间:2016-09-25 05:38:07

标签: javascript jquery jquery-ui

问题更多的是调试/语法错误而非方法。

我在外部js文件中定义了一个函数(模态确认),它返回一个值:

function confirmation(question) {
    var defer = $.Deferred();
    $('<div></div>').html(question).dialog({
      autoOpen: true,
      modal: true,
      title: 'Confirmation',
      buttons: {
        "Delete All Items": function() {
          defer.resolve("true"); //this text 'true' can be anything. But for this usage, it should be true or false.
          $(this).dialog("close");
        },
        "Cancel": function() {
          defer.resolve("false"); //this text 'false' can be anything. But for this usage, it should be true or false.
          $(this).dialog("close");
        }
      },
      close: function() {
        //$(this).remove();
        $(this).dialog('destroy').remove()
      }
    });
}

现在当我尝试调用$(document).ready(function() {内的函数时;我收到 未捕获参考错误

所有必需的文件都包含在调用脚本中。我想了解为什么这样以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

除了最后缺少的花括号,并假设你的&#34;必要文件&#34;包括jquery-ui,你的功能似乎没有任何问题。请参阅此jsfiddle,它不会产生任何错误。

也许问题出现在代码的其他地方?如果您可以发布Minimal, Complete, and Verifiable example

,这可能有所帮助

参考文献:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.theme.css" />

脚本:

$(document).ready(function() {
  confirmation("What's all this, then?");
});

function confirmation(question) {
    var defer = $.Deferred();
    $('<div></div>').html(question).dialog({
      autoOpen: true,
      modal: true,
      title: 'Confirmation',
      buttons: {
        "Delete All Items": function() {
          defer.resolve("true"); //this text 'true' can be anything. But for this usage, it should be true or false.
          $(this).dialog("close");
        },
        "Cancel": function() {
          defer.resolve("false"); //this text 'false' can be anything. But for this usage, it should be true or false.
          $(this).dialog("close");
        }
      },
      close: function() {
        //$(this).remove();
        $(this).dialog('destroy').remove()
      }
    });
}
相关问题