2013-05-10 82 views
2

我还没有能够解释相关问题的答案(到我的知识水平),所以...Javascript .onload在IE中不能触发? window.open参考问题?

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

请任何人都可以向我解释为什么是这样/我做错了什么?这是否与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> 

UPDATE 感谢您对新窗口的onload指针 - 我已经走了这个解决方案现在:Setting OnLoad event for newly opened window in IE6 - 简单地检查DOM并延迟onload - 为IE7/8/9工作。

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

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

http://stackoverflow.com/questions/3030859/detecting-the-onload-event-of-a-window-opened-with-window-open – Ian 2013-05-10 14:37:18

回答

3

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

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

function doStuff() { 
     //...   
    } 

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

你说得对,负责人过早起火。因为目标HTML文件不存在,所以我实际上找不到一种简单的方法将您的解决方案应用到我的页面上,但您的答案使我朝正确的方向发展。非常感谢! – soba3 2013-05-10 16:34:00