getElementbyID returns Null

getElementbyID returns Null

本文关键字:Null returns getElementbyID      更新时间:2023-09-26

我正在尝试创建一个javascript调用,onclick将创建一个页面特定部分的新窗口,并打印它。

为此,我正在修改其他人的SF答案,该答案试图做类似的事情

<div class="patienspecials clearfix" id="print_div1">
    <h1>Bla bla bla</h1> 
    <a href="#" onclick="printInfo(print_div1)"><img 
        class="alignnone size-full wp-image-6196" alt="print-icon" 
        src="#" width="92" height="28" /></a>
</div>

我正在尝试将div print_div1作为此函数的参数传递给该函数 -

<script type="text/javascript">
function printInfo(ele) {
    var openWindow = window.open("", "title", "attributes");
    openWindow.document.write(document.getElementById(ele));
    openWindow.document.close();
    openWindow.focus();
    openWindow.print();
    openWindow.close();
}
</script>

但是,当我运行脚本时,print 命令只是创建一个带有文本"null"的新页面。

我很确定我在getElementById上做错了什么,你们对如何做到这一点有什么想法吗?仍然是一个菜鸟,将不胜感激!

干杯

printInfo(print_div1)将传递ID为print_div1的元素,而不是将字符串传递'print_div1'

只需更新您的 JavaScript 以使用正在传递的元素,而不是尝试将其用作字符串 ID 来查询:

<script type="text/javascript">
function printInfo(ele) {
    var openWindow = window.open("", "title", "attributes");
    //no longer need to select the element by ID, just use it
    openWindow.document.write(ele);
    openWindow.document.close();
    openWindow.focus();
    openWindow.print();
    openWindow.close();
}
</script>

如果您出于某种原因确实想使用 document.getElementById(),只需确保在内联事件中引用字符串 id:

<div class="patienspecials clearfix" id="print_div1">
    <h1>Bla bla bla</h1> 
    <!-- Notice the quotes around 'print_div1' -->
    <a href="#" onclick="printInfo('print_div1')"><img 
        class="alignnone size-full wp-image-6196" alt="print-icon" 
        src="#" width="92" height="28" /></a>
</div>

更改任何一个(但不是两个)应该可以正常工作。希望这有帮助!

这是因为您传递的是未定义的变量print_div1而不是字符串。 用途:

<a onclick="printInfo('print_div1')">...</a>