问题
If I remember correctly, I once saw a method to bind event listeners to every single element that matches a certain criteria, a query selector maybe. Looking for it again I cannot find anything other than people highly dependent on jQuery but I prefer a real simple way to achieve this.
Anyone knows what is this method called?
回答1:
The method you are looking for is called event capturing. You can do it like this:
document.querySelector('body').addEventListener('click', function(evt) {
// Do some check on target
if ( evt.target.classList.contains('some-class') ) {
// DO CODE
}
}, true); // Use Capturing
回答2:
I wrote a more general-purpose function which takes a selector, event-type, and a handler function, akin to jQuery's on
function:
/** adds a live event handler akin to jQuery's on() */
function addLiveEventListeners(selector, event, handler){
document.querySelector("body").addEventListener(
event
,function(evt){
var target = evt.target;
while (target != null){
var isMatch = target.matches(selector);
if (isMatch){
handler(evt);
return;
}
target = target.parentElement;
}
}
,true
);
}
For example, the following will be called for any click on a div, even if it was added to the DOM at a later time:
addLiveEventListeners("div", "click", function(evt){ console.log(evt); });
This works on all modern browsers and Microsoft Edge. To make it work in IE9 -- IE11 the test target.matches(selector)
should be modified like so:
var isMatch = target.matches ? target.matches(selector) : target.msMatchesSelector(selector);
and then the test if (isMatch)
will work for those browsers as well.
See also my answer for Adding event listeners to multiple elements which adds the event listeners to the elements themselves rather than to body
.
来源:https://stackoverflow.com/questions/33898188/event-listener-for-current-and-future-elements-without-jquery