到目前为止(以我的知识水平)我还没有弄明白相关问题的答案,所以...
我有一个简单的脚本(使用 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 并延迟加载 - 适用于 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();
最佳答案
会不会是你打开的页面在你设置事件处理器之前触发了'onload'事件printWindow.onload = ...
?
您可以考虑在“printWindow.html”页面中包含一些 javascript。假设您添加了一个简短的 <script>var printWindowLoaded = true;</script>
在页面的末尾。然后你的主脚本会做这样的事情:
function doStuff() {
//...
}
if (printWindow.printWindowLoaded)
doStuff();
else
printWindow.onload = doStuff;
关于Javascript .onload 不在 IE 中触发? window.open 引用问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484546/