当动态创建的对象插入到DOM中时

When are dynamically created objects inserted into the DOM?

本文关键字:DOM 中时 插入 对象 动态 创建      更新时间:2023-09-26

我有以下代码:

$(function () {
    var html = $('<div></div>');
    html.load('preview.html', function (responseText, textStatus, XMLHttpRequest) {
        $('#some_id_in_loaded_html')...
    }
    html.dialog();
}

但是在IE7中,回调函数中的jQuery选择器失败了,因为它找不到指定的ID。

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

注意,这个问题很容易通过使用$('#some_id_in_loaded_html',this)
来纠正。

$("#foo")使用document作为上下文进行搜索,因此不返回任何内容,因为htmldiv(及其所有后代包括具有该ID的元素)不是DOM的一部分。

您必须首先将htmldiv插入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

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