Attaches an event listener to all the provided targets.
- Use
Array.prototype.forEach()
andEventTarget.addEventListener()
to attach the providedlistener
for the given eventtype
to alltargets
.
代码实现
const addEventListenerAll = (targets, type, listener, options, useCapture) => {
targets.forEach(target =>
target.addEventListener(type, listener, options, useCapture)
);
};
addEventListenerAll(document.querySelectorAll('a'), 'click', () =>
console.log('Clicked a link')
);
// Logs 'Clicked a link' whenever any anchor element is clicked
翻译自:https://www.30secondsofcode.org/js/s/add-event-listener-all