开发者

Callback after loading scripts works when preceded by alert and doesn't when I delete the alert

开发者 https://www.devze.com 2023-02-11 18:47 出处:网络
First, I load some scripts.Then, once they\'re loaded, I bind those scripts to the relevant objects.Everything works great when I have the alert() statement there, and fails (i.e. jEditable does not b

First, I load some scripts. Then, once they're loaded, I bind those scripts to the relevant objects. Everything works great when I have the alert() statement there, and fails (i.e. jEditable does not bind) when I don't.

// Load two scripts, execute editor_callback when both are loaded
$(document).ready(function() {

  var scripts = 0;

  var update_scripts = function() {
    scripts++;
    if (scripts == 2)  {
      editor_callback();
    }
  };

  // Load jEditable
  $.getScript('js/jquery.jeditable.min.js', update_scripts());

  // Load Elastic textareas (if needed)
  if (!jQuery().elastic) {
    $.getScript('js/jquery.elastic.js', update_scripts());
  }
  else {
    update_scripts();
  }

});

function editor_callback() {

  //alert ("In editor_callback()");

  $('.edit_area').editable('editable/update', { 
      type      : 'textarea',
      cancel    : 'Cancel',
      submit    : 'OK',
      indicator : 'Saving...',
      tooltip   : 'Click to edit...'
  });

  $('textare开发者_Go百科a').live("click", function() {$(this).elastic()});
}


Its becouse you are executing the function right away and not waiting for the script to load.

Remove the () after update_scripts, so it will point to the update_scripts function, instead of executing it right away.

Your code should look like this

$.getScript('js/jquery.jeditable.min.js', update_scripts);

As to why adding the alert in the code works: alert paused the current code execution, so the next line (.editable) was waiting for the alert box to close, by that time the scripts were loaded already.


You could use console logging if you're using a javascript debugger that supports it (e.g. firebug or chrome) like this:

console.log("In editor_callback()")

Saves you from clicking the alerts as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消