簡體   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