Event Delegation Pattern with addEventListener and nested elements in buttons

假装没事ソ 提交于 2019-12-20 04:59:09

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/36121179/event-delegation-pattern-with-addeventlistener-and-nested-elements-in-buttons

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