简体   繁体   English

TypeError:document.getElementById(...)在addEventListener上为null

[英]TypeError: document.getElementById(…) is null on addEventListener

I wanted to add some code on clicking of a Div element with id "div_click1". 我想在单击ID为“ div_click1”的Div元素时添加一些代码。 For that I added following code to my custom js 为此,我在自定义js中添加了以下代码

document.getElementById("#div_click1").addEventListener('click', function(){    
// code
},false)

I did not see any error because of this code till I had to reinstall wamp. 在重新安装wamp之前,我没有看到任何由于此代码引起的错误。

I tried fixes suggested for similar issues but though they stopped the issue but also made it do nothing when the div was clicked. 我尝试了针对类似问题的修复建议,但尽管它们已停止了该问题,但在单击div时也使其无济于事。

Will appreciate any help on the topic. 将不胜感激有关该主题的任何帮助。 Thanks!! 谢谢!!

You have to use the same ID in the function call as you use in the element. 您必须在函数调用中使用与元素中相同的ID。

You must not add a hash sign in front of it. 您不得在其前面添加井号。

A hash sign indicates an id in selector syntax. 哈希符号表示选择器语法中的ID。 The getElementById function gets an element by its ID, not by a selector, so you have to pass it an ID, not a selector. getElementById函数通过元素的ID而不是选择器来获取元素,因此您必须将其传递给ID而不是选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM