我正在尝试对弹出窗口的 DOM 执行操作,但由于某种原因ready
,在 DOM 中没有任何内容之前,该事件会立即为弹出窗口触发。
我知道 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
。为什么呢?
有什么建议吗?
谢谢!