我有一个猫构造函数,我想将 eventListener 添加到我的所有猫对象中,因此当我单击它们时,计数器会增加。我不想手动一一添加事件。有没有办法为所有新对象添加事件?谢谢
var counter = document.getElementById("counter").innerHTML;
var Cat = function(name , source , width) {
this.name = name;
this.image = new Image(width);
this.image.src = source;
document.body.appendChild(this.image);
}
var poplinre = new Cat("Poplinre" , "images/poplinre.jpg" , 500);
var chewie = new Cat("Chewie" , "images/chewie.jpg" , 500);
最佳答案
您可以全局监听点击事件并仅定位您想要的图像。这种方式称为事件委托(delegate),这个article给你一些解释。
简而言之,您在公共(public)父节点上监听 click
事件,并且仅针对所需的元素。在你的情况下,你必须实现类似的东西:
document.body.addEventListener('click', e => {
if (e.target && e.target.nodeName === 'IMG' && e.target.classList.contains('cat')) {
//only the image is targeted
}
});
var Cat = function(name , source , width) {
this.name = name;
this.image = new Image(width);
this.image.src = source;
this.image.classList.add('cat');
document.body.appendChild(this.image);
}
关于javascript - addEventlistener 到 javascript 中的所有新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528601/