gpt4 book ai didi

javascript - 事件委托(delegate)问题

转载 作者:行者123 更新时间:2023-11-30 14:36:41 26 4
gpt4 key购买 nike

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

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>

最佳答案

注意:您收到错误是因为您在 querySelectorAll 的返回值上调用 addEventListener,这是一个 没有名为 addEventListener 的函数的 NodeList。使用 querySelector 而不是 querySelectorAll


要实现事件委托(delegate),您必须在元素的祖先之一上设置事件监听器(例如 #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>

关于javascript - 事件委托(delegate)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50321518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com