简体   繁体   中英

Function cannot be called in $(document).ready(function() {

The questionis more of a debuggin/syntax error rather approach .

I have a function(modal confirmation) defined in an external js file which returns a value as such :

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()
      }
    });
}

Now when I try to call the function inside the $(document).ready(function() { ; I get an Uncaught Reference Error .

All the necessary files have been included in calling script. I would like to understand why is this and how i can solve the issue?

Except for the missing curly-brace at the end, and assuming your "necessary files" include jquery-ui, there doesn't seem to be anything wrong with your function. See this jsfiddle , which does not generate any error.

Perhaps the problem is elsewhere in your code? It may help if you can post a Minimal, Complete, and Verifiable example .

References:

<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" />

Script:

$(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()
      }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM