【发布时间】: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