开发者

How to wait for a jQuery function to finish before moving on?

开发者 https://www.devze.com 2023-01-23 15:42 出处:网络
So right now I have the code $(\'[name=dept]\').live(\'change\',function() { $(\'#course\').load(\'getCla.php?dept=\'+$(this).val());

So right now I have the code

$('[name=dept]').live('change',function() {
$('#course').load('getCla.php?dept='+$(this).val());
$('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
});

Basically, what it does is propagate a form select menu after a value is chosen. The problem is, the third line doesn't have its intended action, it it tries to execute before the 2nd line finishes filling the list.开发者_JAVA技巧

Is there a way to make the 3rd line wait until the list has finished propagating? (As filling the list reformats the list).


Use the callback parameter of .load(), like this:

$('#course').load('getCla.php?dept='+$(this).val(), function() { 
  $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
});

The callback runs when the response comes back and the #course element has the new content. It also receives the returned html from the server as the first argument, if you need it for any reason.

Also since your initial selector is so expensive, I highly recommend .delegate() here, like this:

$('body').delegate('[name=dept]', 'change', function() {
  $('#course').load('getCla.php?dept='+$(this).val(), function() { 
    $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
  });
});


use the call back function in jQuery load()

Like This:

$('[name=dept]').live('change',function() {
  $('#course').load('getCla.php?dept='+$(this).val(), function (responseText, textStatus, xhr) {
    $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
  });
});
0

精彩评论

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