0

thing.addEventListener(...)javascript中使用自定义事件调用时,有没有办法运行一些代码来设置触发器?这是一个例子:

var bong = new CustomEvent("bong");
element1.addEventListener('bong', (e) => console.log(`${e.target.id} bonged`));

现在我想bong在元素发生某些事情时被触发。比如说,mousedownmouseup。我可以写:

var bong = new CustomEvent("bong");
function setBongTriggers(element) {
    element.addEventListener('mousedown', (e) => e.target.dispatchEvent(bong));
    element.addEventListener('mouseup', (e) => e.target.dispatchEvent(bong));
}

element1.addEventListener('bong', (e) => console.log(`${e.target.id} bonged`));
setBongTriggers(element);

但我将不得不为许多元素执行此操作,我不想setBongTriggers对每个元素都进行调用。有没有办法告诉addEventListener设置触发器?

4

0 回答 0