简体   繁体   English

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

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

Why the following code generates TypeError: document.getElementById("docPrint") 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();

You are operating across two windows. 您正在两个窗口中进行操作。

printwindow.document.write
document.getElementById

If you want to get the element you created in the popup then you have to call it's gEBI method. 如果要获取在弹出窗口中创建的元素,则必须调用它的gEBI方法。

printwindow.document.write
printwindow.document.getElementById

Prepend printwindow. printwindow. to each instance of document.getElementById : document.getElementById每个实例:

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

You need to prefix your calls to document.getElementById with 'printwindow': 您需要在对document.getElementById的调用之前加上“ printwindow”前缀:

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

You might also want to keep a reference to the element in a variable, to avoid the boilerplate 您可能还想在变量中保留对元素的引用,以避免重复样板

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