2010-11-04 166 views
0

所以現在我的代碼如何在繼續之前等待jQuery函數完成?

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

基本上,它的作用是選擇了一個值後傳播形式的選擇菜單。問題是,第三行沒有預期的動作,它在第二行完成填充列表之前嘗試執行。

有沒有辦法讓第三行等到列表完成傳播? (填充列表重新格式化列表)。

回答

5

使用回調參數的.load(),像這樣:

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

回調運行時,響應回來和#course元素具有新的內容。它也接收從服務器返回的html作爲第一個參數,如果您出於任何原因需要它。

此外,由於您最初的選擇是如此昂貴,我強烈建議.delegate()這裏,像這樣:

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

。我似乎無法在你之前得到我的答案......似乎總是落後一步。但我確實打敗了你這一個..我其實是supprised你沒有提供一個答案http://stackoverflow.com/questions/4084095/help-in-jquery-selectors – 2010-11-04 00:47:34

+0

@約翰 - 可能是因爲我睡着了: )與任何謠言相反,我確實每天睡4-6個小時:) – 2010-11-04 00:49:18

+0

聽起來很正確。那關於我得到的所有睡眠。 – 2010-11-04 00:50:12

2

使用回撥功能jQuery load()

這樣的:

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

謝謝!尼克先回答,所以我必須接他,但你仍然幫助! – Parker 2010-11-04 00:42:21

+0

@皮克......沒問題......尼克總是先回答.. lol :) – 2010-11-04 00:44:09

相關問題