2011-12-22 44 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(),这将可能是你的异步回调之前运行插入(在某些情况下,但也许以后?)。