[英]“addEventListener is not a function” problem
I've seen some people having this problem but I can't find a solution that can fit my code. 我见过有人遇到此问题,但找不到适合我代码的解决方案。 I'm trying to build a memory game using many <img>
tags inside a <div>
one, so that in Javascript I can make an addEventListener that can call the same function for different objects. 我正在尝试使用<div>
<img>
标记内的许多<img>
标记来构建记忆游戏,以便在Javascript中可以创建一个addEventListener,可以为不同的对象调用相同的函数。 But when I try to open it on Chrome it says: 但是,当我尝试在Chrome上打开它时,它说:
main2.js:21 Uncaught TypeError: img_deck.addEventListener is not a function
Below is my code: 下面是我的代码:
HTML: HTML:
<body onload="sortDeck()">
<div class="deck">
<tr>
<th> <img id="0" src="back.jpg"> </th>
<th> <img id="1" src="back.jpg"> </th>
<th> <img id="2" src="back.jpg"> </th>
<th> <img id="3" src="back.jpg"> </th>
</tr>
<tr>
<th> <img id="4" src="back.jpg"> </th>
<th> <img id="5" src="back.jpg"> </th>
<th> <img id="6" src="back.jpg"> </th>
<th> <img id="7" src="back.jpg"> </th>
</tr>
<tr>
<th> <img id="8" src="back.jpg"> </th>
<th> <img id="9" src="back.jpg"> </th>
<th> <img id="10" src="back.jpg"> </th>
<th> <img id="11" src="back.jpg"> </th>
</tr>
</div>
</body>
JS: JS:
var img_deck = document.getElementsByTagName("DIV");
img_deck.addEventListener("click", clickCard);
As the method you are using suggests, getElementsByTagName
returns more than one element, as an array. 正如您使用的方法所建议的那样, getElementsByTagName
作为数组返回多个元素。 You could iterate over this array like so: 您可以像这样遍历此数组:
const divs = document.getElementsByTagName("DIV");
for (const div of divs) {
div.addEventListener("click", clickCard);
}
document.getElementById
will return an html element which id is same with param. document.getElementById
将返回一个id与param相同的html元素。
Whereas document.getElementsByTagName
returns the array of html elements which tags are same with the param. 而document.getElementsByTagName
返回html元素的数组,这些html标签与param相同。
So in your script, 所以在您的脚本中
var img_deck = document.getElementsByTagName("DIV");
img_deck.addEventListener("click" , clickCard);
img_deck will have the array of elements which tags are 'DIV'
So you should make a loop for img_deck and add event listener for every element inside that loop img_deck将具有标记为'DIV'
的元素数组,因此您应为img_deck制作一个循环,并为该循环中的每个元素添加事件监听器
like this 像这样
var img_deck = document.getElementsByTagName("DIV");
img_deck.forEach(function(elem){
elem.addEventListener("click", clickCard);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.