Event listener for current and future elements Without jQuery

流过昼夜 提交于 2019-11-29 14:53:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!