【问题标题】:Javascript .onload not firing in IE? window.open reference issue?Javascript .onload 没有在 IE 中触发? window.open 参考问题?
【发布时间】:2013-05-05 06:33:12
【问题描述】:

到目前为止,我还无法理解相关问题的答案(根据我的知识水平),所以...

我有一个简单的脚本(使用 jQuery),它打开一个新窗口并将父级的某些内容添加到子级内的指定容器中。我不确定这是我的方法错误还是我只是错过了一个步骤 - 在新窗口上运行的脚本在 window.onload 函数之外时在 IE 中运行,但这会破坏 FF,并且 FF 很高兴当它在window.onload 内时,但是 IE 中的新窗口似乎没有做任何事情(没有警报,没有添加内容,nada)。

请任何人向我解释为什么会这样/我做错了什么?是否与对window.open 的引用有关?

这是脚本:

var printPage = function(container){

    $('.printButton').click(function(){

        var printWindow = window.open('printWindow.html');  

        var contentFromParent = $(container).eq(0).html();   

        /*works for IE, but not FF
        printWindow.alert('works for IE, but not FF');  
        printWindow.document.getElementById('wrap').innerHTML = contentFromParent;*/

        /*works for FF and Chrome but not IE:*/
        printWindow.onload = function(){
            printWindow.alert('works for FF and Chrome but not IE');
            printWindow.document.getElementById('wrap').innerHTML = contentFromParent;          
        }

        /*I also tried:
        $(printWindow.document).ready(function(){
            printWindow.alert('load the page, fill the div');
            printWindow.document.getElementById('wrap').innerHTML = contentFromParent;
        }); //works for IE, not working for FF/Chrome*/
    })  
}
printPage('#printableDiv');

HTML:

<div id="wrap">
    <button href="#" class="printButton">Print</button>
    <div id="printableDiv"> 
        <p>I want to see this content in my new window please</p>
    </div>
</div>

更新 感谢您在新窗口中关于 onload 的指示 - 我现在已经使用了这个解决方案:Setting OnLoad event for newly opened window in IE6 - 只需检查 DOM 并延迟 onload - 适用于 IE7/8/9。

我不确定您是否称其为“优雅”的解决方案,但它确实有效!进一步的 cmets,特别是如果您认为这是有缺陷的,将不胜感激。谢谢。

var newWinBody;
function ieLoaded(){
    newWinBody = printWindow.document.getElementsByTagName('body');
    if (newWinBody[0]==null){
        //page not yet ready
        setTimeout(ieLoaded, 10);
    } else {
        printWindow.onload = function(){
            printWindow.alert('now working for all?');
            printWindow.document.getElementById('wrap').innerHTML = contentFromParent;          
        }
    }
}
IEloaded();

【问题讨论】:

标签: javascript jquery onload window-object


【解决方案1】:

你打开的页面会不会在你设置事件处理程序printWindow.onload = ...之前触发'onload'事件?

您可以考虑在您的“printWindow.html”页面中包含一些 javascript。假设您在页面末尾添加了一个简短的&lt;script&gt;var printWindowLoaded = true;&lt;/script&gt;。然后你的主脚本会做这样的事情:

function doStuff() {
        //...          
    }

if (printWindow.printWindowLoaded)
    doStuff();
else
    printWindow.onload = doStuff;

【讨论】:

  • 你是对的,onload 启动得太早了。我实际上找不到将您的解决方案应用于我的页面的简单方法,因为目标 html 文件不存在,但您的回答为我指明了正确的方向。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-09-14
  • 2011-05-20
  • 1970-01-01
  • 2019-12-13
  • 2012-06-08
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
相关资源
最近更新 更多