2012-04-27 103 views
1

我只是試着用jQuery的.load方法改變我的頁面內容。爲什麼jquery在.load()後面看到頁面的變化?

雖然內容變化沒有問題,我發現jQuery的仍然「看到」舊的內容,如果我試圖選擇的東西,一個例子:

頁:

<div id="mycontentarea"> 
    <div id="myfirstcontent"></div> 
    <div id="mysecondcontent"></div> 
</div> 

更換內容:

<div id=mythirdcontent"></div> 
<div id=myfourthcontent"></div> 

的javascript:

// replace original content 
$('#mycontentarea').load('replacement.html'); 
// print out the id of the first child 
console.log($("#mycontentarea").children().attr("id")); 

控制檯將打印出「myfirstcontent」而不是「mythirdcontent」 - 爲什麼?

+0

如果您使用'load'來動態地將事件重新附加到動態內容,則需要使用jQueries'live'或'delegate'。 – ppumkin 2012-04-27 10:45:14

回答

6

由於load是異步的,您的console.log調用在更換髮生之前執行。

將依賴於呼叫的結果load到這是成功完成後執行的回調任何代碼:

$('#mycontentarea').load('replacement.html', function() { 
    //Anything in here is executed once the content has been returned successfully 
    console.log($("#mycontentarea").children().attr("id")); 
}); 

從文檔上load

如果一個「完整「提供回調,在 後處理和HTML插入已執行後執行。回調是 爲jQuery集合中的每個元素觸發一次,並且依次爲每個DOM元素設置 。

相關問題