简体   繁体   English

未捕获的类型错误:document.getElementsByClassName(...).addEventListener 不是函数

[英]Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function

I need to listen for clicks on <input/> elements.我需要监听对<input/>元素的点击。 This is my code这是我的代码

<script>
    document.getElementsByClassName("form-control").addEventListener("click", function(e){
      alert("Listener added");
    });
</script>    

But I'm getting this error:但我收到此错误:

Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function

Any ideas?有任何想法吗?

Instead of returning single element getElementsByClassName() returns collection of elements.That's why we have to loop that collection of elements or simply you can overcome this problem by adding document.getElementsByClassName('form-control')[0] getElementsByClassName()不是返回单个元素,而是返回元素集合。这就是为什么我们必须循环该元素集合,或者您可以通过添加document.getElementsByClassName('form-control')[0]来解决这个问题

Here,I rewrite the code:在这里,我重写了代码:

` `

document.getElementsByClassName("form-control")[0].addEventListener("click", function(e){
  alert("Listener added");
});

` `

Hope I was able to answer your question.希望我能够回答你的问题。 JavaScript event handling can be useful for you. JavaScript事件处理可能对您有用。

The reason why you are getting this error is because getElementsByClassName returns an array of elements but you need to have a single element in order to add an event listener.您收到此错误的原因是因为 getElementsByClassName 返回一个元素数组,但您需要有一个元素才能添加事件侦听器。 If you want to add event listener to all elements, you can simply loop through the array as shown below.如果你想为所有元素添加事件监听器,你可以简单地循环遍历数组,如下所示。

document.getElementsByClassName("form-control").forEach(element => {
  element.onclick = event => {
    alert("Listener added");
  }
}); 

If you want to add event listener to a specific element, you can simply access it by indexing the array.如果要将事件侦听器添加到特定元素,只需通过索引数组即可访问它。

document.getElementsByClassName("form-control")[0].addEventListener("click", function(e){
  alert("Listener added");
}); 

You can also use ids for specific elements in order to access them more easily.您还可以为特定元素使用 id,以便更轻松地访问它们。

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

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