繁体   English   中英

为什么TypeError:document.getElementById()为null

[英]Why TypeError: document.getElementById() is null

为什么以下代码生成TypeError: document.getElementById("docPrint") is null

var printwindow = window.open('', '', 'fullScreen=no');
printwindow.document.write('<iframe id="docPrint" width="100%" height="100%" src="http://localhost:8080/hiring/docs/Keneth _1340800082258/Keneth _resume_1340800082258.pdf"></iframe>');
printwindow.self.focus();
document.getElementById('docPrint').focus();
document.getElementById('docPrint').contentWindow.print();

您正在两个窗口中进行操作。

printwindow.document.write
document.getElementById

如果要获取在弹出窗口中创建的元素,则必须调用它的gEBI方法。

printwindow.document.write
printwindow.document.getElementById

printwindow. document.getElementById每个实例:

printwindow.document.getElementById('docPrint').focus();
printwindow.document.getElementById('docPrint').contentWindow.print();

您需要在对document.getElementById的调用之前加上“ printwindow”前缀:

printwindow.document.getElementById('docPrint').focus();
printwindow.document.getElementById('docPrint').contentWindow.print();

您可能还想在变量中保留对元素的引用,以避免重复样板

var el = printwindow.document.getElementById('docPrint');
el.focus();
el.contentWindow.print();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM