简体   繁体   中英

Event Delegation Pattern with addEventListener and nested elements in buttons

I have a set of buttons in a parent. Each containing an SVG icon which are added programmatically. I'm attempting to listen on the parent element and then use event delegation to trigger different functionality for particular buttons, but what lands up happening is I get event targets of the contained svg's or paths rather than the buttons themselves. Is there a way to leverage event bubbling, or change the way I'm doing this to still avoid adding a ton of event handlers, and trigger the events I need? Heres some simplified code:

<div class="parent">
    // I have a whole lot of these added to the page programmatically
    <button class="some-unique-class">
        <svg> //... </svg>
    </button>
</div>

and then in my javascript :

document.querySelector('.parent').addEventListener('click', function(event) {

    //.. I always want to trigger events on the buttons, not
    // on the svg's and their paths.  
});

Using JQuery I'm able to do this easily, by listening on a parent element and then specifying the element, but I'd like to do this in vanilla JS.

Any help would be massively appreciated.

I guess the simplest way would be to have a function like jquery's closest :

 function closest(elem, selector) { do { if(elem.matches(selector)) return elem; elem = elem.parentNode; } while(elem); } document.querySelector('.parent').addEventListener('click', function(e) { var btn = closest(e.target, 'button'); btn.style.backgroundColor = 'red'; }); 
 <div class="parent"> <button class="some-unique-class"> <b>hey</b> </button> <button class="some-unique-class"> <b>hey</b> </button> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM