javascript $(document).ready() 立即触发 window.open() 上下文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19671220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:25:51  来源:igfitidea点击:

$(document).ready() fires immediately for window.open() context

javascriptjquerywindow.opendocument-ready

提问by M Miller

I'm trying to perform operations on the DOM of a popup window, but for some reason the readyevent fires immediately for the popup, before there's anything in the DOM.

我正在尝试对弹出窗口的 DOM 执行操作,但由于某种原因ready,在 DOM 中没有任何内容之前,该事件会立即为弹出窗口触发。

I know that jQuery can access the DOM of the popup window by using context, and that I can manage to do it by using setTimeoutto delay any action until a reasonable amount of time has passed.

我知道 jQuery 可以通过使用上下文访问弹出窗口的 DOM,并且我可以通过使用setTimeout延迟任何操作直到经过合理的时间来设法做到这一点。

http://jsfiddle.net/GVcjn/

http://jsfiddle.net/GVcjn/

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

Also, I know it's not jQuery's fault. If I add console.log(popup.document.readyState);immediately after var popup = window.open('/test');, it prints complete. Why, though?

另外,我知道这不是 jQuery 的错。如果我在console.log(popup.document.readyState);之后立即添加var popup = window.open('/test');,它会打印complete. 为什么呢?

Any advice?

有什么建议吗?

Thanks!

谢谢!

回答by joseramonc

Have you tried this?

你试过这个吗?

popup.onload = function () {
  //lot of things
};

With jQuery load, according to the documentation http://api.jquery.com/load-event/is:

使用 jQuery 加载,根据文档http://api.jquery.com/load-event/是:

$(popup).load(function() {
  // things
});

This question answer something similar too: How can I access the dom tree of child window?Hope it helps you

这个问题也回答了类似的问题:如何访问子窗口的 dom 树?希望对你有帮助