动态创建的对象何时插入到 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) 可以轻松纠正此问题
I have the following code:
$(function () {
var html = $('<div></div>');
html.load('preview.html', function (responseText, textStatus, XMLHttpRequest) {
$('#some_id_in_loaded_html')...
}
html.dialog();
}
However in IE7, the jQuery selector in the callback function fails because it can't find the specified ID. It works fine in Firefox.
Why is this occurring and which is the correct behavior (according to the standards)?
Note that this problem is easily corrected by using $('#some_id_in_loaded_html',this)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$("#foo")
使用document
作为搜索上下文,因此不会返回任何内容,因为html
div (和它的所有后代(包括具有该 ID 的元素)都不是 DOM 的一部分。您必须首先将
html
div 插入 DOM,例如html.appendTo("body");
。然后,所有后代也会自动出现在 DOM 中,并且$("#foo")
可以工作。使用实际搜索功能(
querySelectorAll
)的测试用例:http://jsfiddle.net/k7muh/< /a>.$("#foo")
usesdocument
as the context to search in, and as such does not return anything because thehtml
div (and all its descendants including the element with that ID) are not part of the DOM.You have to insert the
html
div to the DOM first, likehtml.appendTo("body");
. All descendants are then automatically also in the DOM, and$("#foo")
works.Test case using actual search function (
querySelectorAll
): http://jsfiddle.net/k7muh/.在这种情况下,我认为它是在您调用
.dialog()
时插入的,它可能会在异步回调之前运行(但在某些情况下可能会稍后运行?)。In this case, I think it's inserted when you call
.dialog()
, which will probably run before your async callback (but perhaps later in some cases?).