我正在尝试对弹出窗口的DOM执行操作,但出于某种原因,在{DOM}中有任何内容之前,ready
事件会立即触发弹出窗口。
我知道jQuery可以通过使用上下文来访问弹出窗口的DOM,并且我可以设法通过使用setTimeout
来延迟任何操作,直到经过合理的时间。
(function ($) {
$(function () {
var popup = window.open('/test');
// JSFiddle 404 page
$(popup.document).ready(function () {
// Should fire when the DOM of the 404 page has loaded...
$('h2', popup.document).css('color', '#FF0000');
// Change the color of the header to red.
console.log($('h2', popup.document).length);
// Should log 1
// Logs 0, though, because this function fires immediately, before the DOM loads.
});
setTimeout($.proxy(function () {
// This will definitely fire after the DOM of the 404 page is loaded.
var popup = this;
$('h2', popup.document).css('text-decoration', 'underline');
// This works, because it waited long enough.
// But I don't want to guess how long it will take the DOM to load....
}, popup), 5000);
// After 5 seconds...
});
})(jQuery);
另外,我知道这不是jQuery的错。如果我在console.log(popup.document.readyState);
之后立即添加var popup = window.open('/test');
,则会打印complete
。为什么呢?
有什么建议吗?
谢谢!
答案 0 :(得分:7)
你试过这个吗?
popup.onload = function () {
//lot of things
};
使用jQuery加载,根据文档http://api.jquery.com/load-event/是:
$(popup).load(function() {
// things
});
这个问题也回答了类似的问题:How can I access the dom tree of child window? 希望它能帮到你