在按钮中具有addEventListener和嵌套元素的事件委托模式 [英] Event Delegation Pattern with addEventListener and nested elements in buttons

查看:82
本文介绍了在按钮中具有addEventListener和嵌套元素的事件委托模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在父母中有一组按钮.每个都包含以编程方式添加的SVG图标.我试图监听父元素,然后使用事件委托来为特定按钮触发不同的功能,但是正在发生的事情是我得到了所包含的svg或路径的事件目标,而不是按钮本身.有没有一种方法可以利用事件冒泡,或者更改我执行此操作的方式,从而仍然避免添加大量事件处理程序并触发我需要的事件?这里是一些简化的代码:

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>

,然后在我的javascript中:

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.  
});

使用JQuery,我可以轻松地做到这一点,方法是侦听父元素,然后指定该元素,但是我想在普通JS中做到这一点.

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.

任何帮助将不胜感激.

推荐答案

我想最简单的方法就是拥有类似jquery的closest:

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>

这篇关于在按钮中具有addEventListener和嵌套元素的事件委托模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆