Javascript 事件委派问题
我正在学习javascript,在事件委派方面遇到了问题。我正在测试我在浏览器中完成的内容是否有错误——没有多少错误——并不断收到一条消息,说:Javascript 事件委派问题,javascript,event-delegation,Javascript,Event Delegation,我正在学习javascript,在事件委派方面遇到了问题。我正在测试我在浏览器中完成的内容是否有错误——没有多少错误——并不断收到一条消息,说: thumbs.addEventListener不是一个函数 任何帮助都将不胜感激 这是我的密码: window.addEventListener(“加载”,函数(){ var thumbs=document.queryselectoral(“缩略图”); thumbs.addEventListener(“单击”,函数(e){ }); }); 您正在使
thumbs.addEventListener
不是一个函数
任何帮助都将不胜感激
这是我的密码:
window.addEventListener(“加载”,函数(){
var thumbs=document.queryselectoral(“缩略图”);
thumbs.addEventListener(“单击”,函数(e){
});
});代码>
您正在使用一个数组拇指。要向每个事件侦听器添加事件侦听器,必须循环
var thumbs = document.querySelectorAll("#thumbnails");
thumbs.forEach(function(element){
element.addEventListener("click", function(event) {
// your code
});
});
更新
注意:出现错误是因为您在调用querySelectorAll
的返回值时调用了addEventListener
,它是一个节点列表
,没有名为addEventListener
的函数。使用querySelector
而不是queryselectoral
要实现事件委派,您必须在元素的一个祖先(例如#缩略图
)上设置事件侦听器,然后在单击时,检查事件的目标是否为图像:
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(“缩略图”);
container.addEventListener(“单击”),函数(事件){
var target=event.target;
if(target.matches(“img”)){
console.log(target.title);
}
});代码>
感谢您的快速响应,但我尝试使用事件委派或通过Dom弹出,因此我不必为每个事件分配事件侦听器。使用getElementById(“缩略图”)
将div
作为父对象。好的,这很有帮助。谢谢大家!@拉瑞豪夫,不客气!我还添加了一条关于您遇到的错误的注释。
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
}
});