事件委托问题

Event delegation problems

我正在学习 javascript,但在事件委托方面遇到了问题。我正在测试我在浏览器中完成的错误——不多——并不断收到一条消息说:

thumbs.addEventListener is not a function

如有任何帮助,我们将不胜感激。

这是我的代码:

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> 

您正在使用数组 thumbs。要为每个事件监听器添加一个事件监听器,您必须循环。

  var thumbs = document.querySelectorAll("#thumbnails");
  thumbs.forEach(function(element){
    element.addEventListener("click", function(event) {
      // your code
   });
  });

Update

  var thumbs = document.getElementById("thumbnails");
    thumbs.addEventListener("click", function(event) {
      // your code
      console.log(event.target);
   });

注意: 您收到错误是因为您在 querySelectorAll 的 return 值上调用 addEventListener,这是一个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>