gpt4 book ai didi

javascript - 什么时候将动态创建的对象插入到 DOM 中?

转载 作者:行者123 更新时间:2023-11-29 22:27:32 25 4
gpt4 key购买 nike

我有以下代码:

$(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)

可以轻松解决此问题

最佳答案

$("#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

关于javascript - 什么时候将动态创建的对象插入到 DOM 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8604812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com