2011-12-22 51 views
2

我有以下代碼:何時動態創建的對象插入DOM?

$(function() { 
    var html = $('<div></div>'); 

    html.load('preview.html', function (responseText, textStatus, XMLHttpRequest) { 
     $('#some_id_in_loaded_html')... 
    } 

    html.dialog(); 
} 

然而,在IE7,在回調函數jQuery選擇,因爲它無法找到指定的ID失敗。它在Firefox中正常工作。

爲什麼會發生這種情況,哪些是正確的行爲(根據標準)?

請注意,這個問題很容易通過使用$('#some_id_in_loaded_html',this)

+0

這是在'$(document).ready()'的上下文中運行嗎? – jrummell 2011-12-22 13:54:28

+0

@ jrummell:是的,它全部用一個ready() – tskuzzy 2011-12-22 13:56:48

回答

2

$("#foo")修正使用document的上下文中搜索,因此不返回任何東西,因爲html DIV(和它的所有後代,包括與該ID的元素)不是DOM的一部分。

您必須先將html div插入DOM,如html.appendTo("body");。所有的後代然後自動也在DOM中,並且$("#foo")工作。

使用實際搜索功能的測試用例(querySelectorAll):http://jsfiddle.net/k7muh/

var div = $("<div><div id='foo'></div></div>"); 

// tests to expect div#foo 

console.log(document.querySelectorAll("#foo")); // searches in document and 
                // does not find the element 

console.log(div.get(0).querySelectorAll("#foo")); // searches in the (detached) 
                // div and finds the element 
0

在這種情況下,我認爲這是當你調用.dialog(),這將可能是你的異步回調之前運行插入(在某些情況下,但也許以後?)。