我正在学习javascript并遇到事件委派问题。我正在浏览器中测试我在浏览器中完成的错误 - 并不多 - 并继续收到消息说:
thumbs.addEventListener
不是函数
任何帮助将不胜感激。
这是我的代码:
window.addEventListener("load", function() {
var thumbs = document.querySelectorAll("#thumbnails");
thumbs.addEventListener("click", function(e) {
});
});

<div id="thumbnails">
<img src="http://via.placeholder.com/350x150?text=Battle" title="Battle" />
<img src="http://via.placeholder.com/350x150?text=Luneburg" title="Luneburg" />
<img src="http://via.placeholder.com/350x150?text=Bermuda" title="Bermuda" />
<img src="http://via.placeholder.com/350x150?text=Athens" title="Athens" />
<img src="http://via.placeholder.com/350x150?text=Florence" title="Florence" />
</div>
&#13;
答案 0 :(得分:1)
您正在使用thumbs
数组。要为每个事件添加一个事件监听器,您必须循环。
var thumbs = document.querySelectorAll("#thumbnails");
thumbs.forEach(function(element){
element.addEventListener("click", function(event) {
// your code
});
});
更新
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function(event) {
// your code
console.log(event.target);
});
答案 1 :(得分:1)
注意:您收到错误是因为您在addEventListener
的返回值querySelectorAll
上调用了NodeList
addEventListener
没有名为querySelector
的函数。使用querySelectorAll
代替#thumbnails
。
要实现事件委派,您必须在元素的一个祖先(例如var container = document.querySelector("#thumbnails"); // select the ancestor, use querySelector instead of querySelectorAll
container.addEventListener("click", function(event) { // add the click event listener to it
var target = event.target; // when the click happens, get the target of the click
if(target.matches("img")) { // check if the target is one of our img (the selector passed to "matches" could be any css selector, for example "#thumbnails > img", ...)
console.log(target.title); // use the element, or whatever
}
});
)上设置事件侦听器,然后在单击发生时,检查事件的目标是一张图片:
var container = document.querySelector("#thumbnails");
container.addEventListener("click", function(event) {
var target = event.target;
if(target.matches("img")) {
console.log(target.title);
}
});
示例:强>
<div id="thumbnails">
<img src="http://via.placeholder.com/350x150?text=Battle" title="Battle" />
<img src="http://via.placeholder.com/350x150?text=Luneburg" title="Luneburg" />
<img src="http://via.placeholder.com/350x150?text=Bermuda" title="Bermuda" />
<img src="http://via.placeholder.com/350x150?text=Athens" title="Athens" />
<img src="http://via.placeholder.com/350x150?text=Florence" title="Florence" />
</div>
&#13;
{{1}}&#13;