getElementbyID returns Null
getElementbyID returns Null
我正在尝试创建一个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>
相关文章:
- Firefox-SDK contentScript returns null
- document.getElementById(#mapid) returns null
- JavaScript getElementById returns null
- Javascript getElementByID for asp:Image returns null
- Magento newsletter ajax request returns null
- GetCookie returns NULL
- getElementByID returns null (jsfiddle inside)
- PowerShell getElementByTagName("a") returns NULL
- getElementbyID returns Null
- JavaScript/Node match returns null
- GetElementByID returns null value
- window.onload and getelementbyid returns null
- Angular Factory returns null
- jquery html returns null
- getElementById returns null?
- Postman PUT JSON Returns Null
- document.querySelector() returns null
- get_selectedItems()[0] on RadGrid returns null
- SVG getIntersectionList returns null
- getTargetEl().down('input') of textarea returns null