【问题标题】:Why TypeError: document.getElementById() is null为什么 TypeError: document.getElementById() 为空
【发布时间】:2012-07-11 19:53:58
【问题描述】:

为什么下面的代码会生成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();

【问题讨论】:

  • 有没有考虑到id docPrint 的元素不存在?因为这很可能就是这样。

标签: javascript document getelementbyid


【解决方案1】:

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

printwindow.document.write
document.getElementById

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

printwindow.document.write
printwindow.document.getElementById

【讨论】:

    【解决方案2】:

    您需要在对 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();
    

    【讨论】:

    • 我知道所有答案都是正确的。我接受对我来说更容易理解和简单的一个:)。我都投了。
    【解决方案3】:

    document.getElementById 的每个实例前添加printwindow.

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

    【讨论】:

      猜你喜欢
      • 2012-11-26
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 2010-11-18
      • 2011-10-23
      • 2014-11-13
      • 2011-02-07
      • 2011-10-02
      相关资源
      最近更新 更多