".addEventListener不是函数"为什么会发生此错误? [英] ".addEventListener is not a function" why does this error occur?

查看:1022
本文介绍了".addEventListener不是函数"为什么会发生此错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到".addEventListener不是函数"错误.我一直坚持下去:

I’m getting an ".addEventListener is not a function" error. I am stuck on this:

var comment = document.getElementsByClassName("button");
function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);

<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield">
</div>

推荐答案

您的代码存在的问题是,您的脚本是在html元素可用之前执行的.因为var comment是一个空数组.

The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.

因此,您应该在html元素可用后移动脚本.

So you should move your script after the html element is available.

此外,getElementsByClassName返回html集合,因此,如果需要将事件侦听器添加到元素,则需要执行以下操作

Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following

comment[0].addEventListener('click' , showComment , false ) ; 

如果要将事件侦听器添加到所有元素,则需要遍历它们

If you want to add event listener to all the elements, then you will need to loop through them

for (var i = 0 ; i < comment.length; i++) {
   comment[i].addEventListener('click' , showComment , false ) ; 
}

这篇关于".addEventListener不是函数"为什么会发生此错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆