javascript - addEventlistener 到 javascript 中的所有新对象

标签 javascript addeventlistener

我有一个猫构造函数,我想将 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/

相关文章:

javascript - 我想从 JSON 数据打印出一个列表,其中一个键作为 jquery 中的列表头

javascript - 如何让svg对象做圆周轨迹匀速运动,D3.js

javascript - 带 JS 的 SVG map - 更改悬停时多个路径的状态

javascript - 设置高度动画时元素跳跃

javascript - href 不以 '#' 结尾的 anchor 的 CSS 选择器

ckeditor - 如何更改 CKEditor 元素

javascript - 传递带参数的函数时不触发单击事件

javascript - 无法在 addEventListener 调用的函数内调用函数

javascript - 尝试向 js 文件添加事件监听器

javascript - JS,使用xlink将svg保存为png错误:href