Javascript 何时将动态创建的对象插入DOM?

Javascript 何时将动态创建的对象插入DOM?,javascript,jquery,ajax,internet-explorer,dom,Javascript,Jquery,Ajax,Internet Explorer,Dom,我有以下代码: $(function () { var html = $('<div></div>'); html.load('preview.html', function (responseText, textStatus, XMLHttpRequest) { $('#some_id_in_loaded_html')... } html.dialog(); } $(函数(){ var html=$(''); loa

我有以下代码:

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

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

    html.dialog();
}
$(函数(){
var html=$('');
load('preview.html',函数(responseText、textStatus、XMLHttpRequest){
$(“#一些_id_中加载的_html”)。。。
}
html.dialog();
}
但是在IE7中,回调函数中的jQuery选择器失败,因为它找不到指定的ID。它在Firefox中工作正常

为什么会发生这种情况,哪种行为是正确的(根据标准)

请注意,通过使用
$('u loaded_html'中的某些_id_),可以很容易地纠正此问题,因为
$(“#foo”)
使用
文档
作为搜索上下文,因此不会返回任何内容,因为
html
div(及其所有子体,包括具有该id的元素)不是DOM的一部分

您必须首先将
html
div插入DOM,就像
html.appendTo(“body”);
一样。然后,所有子体也会自动插入DOM中,
$(“#foo”)
工作

使用实际搜索功能的测试用例(
querySelectorAll
):

var div=$(“”);
//期望div#foo的测试
console.log(document.queryselectoral(#foo”);//在文档和
//找不到元素
console.log(div.get(0.queryselectoral(#foo”);//在中搜索(已分离)
//div并查找元素

在这种情况下,我认为它是在调用
.dialog()
时插入的,它可能会在异步回调之前运行(但在某些情况下可能会稍后运行)。

这是在
$(document)的上下文中运行的。
?@jrummell:是的,它都是用ready()包装的
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