Vanilla JS 事件委托——处理目标元素的子元素 [英] Vanilla JS event delegation - dealing with child elements of the target element

查看:23
本文介绍了Vanilla JS 事件委托——处理目标元素的子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 vanilla JS 中进行事件委托.我在这样的容器内有一个按钮

<button id="game-again" class="game-again"><span class="icon-spinner icon"></span><span>再次出发</span>

并按照 David Walsh 的好说明 我正在向按钮的祖先添加一个事件处理程序,例如所以:

this.container.addEventListener('click', function(e){if (e.target && e.target.id == 'game-again') {e.stopPropagation();self.publish('primo:evento');}});

其中 this.container 是 #quiz 元素.这有一半时间有效,但其余时间点击事件的目标是按钮内的跨度之一,所以我的事件处理程序没有被调用.处理这种情况的最佳方法是什么?

解决方案

替代解决方案:

MDN:指针事件

为所有嵌套的子元素添加一个类(.pointer-none)

.pointer-none {指针事件:无;}

你的标记变成

<button id="game-again" class="game-again"><span class="icon-spinner icon pointer-none"></span><span class="pointer-none">再去</span>

当指针设置为 none 时,点击事件不会在这些元素上触发.

https://css-tricks.com/slightly-careful-sub-elements-clickable-things/

I'm trying to do event delegation in vanilla JS. I have a button inside a container like this

<div id="quiz">
    <button id="game-again" class="game-again">
        <span class="icon-spinner icon"></span>
        <span>Go again</span>
    </button>
</div>

And following David Walsh's nice instructions I'm adding an event handler to an ancestor of the button like so:

this.container.addEventListener('click', function(e){
    if (e.target && e.target.id == 'game-again') {
        e.stopPropagation();
        self.publish('primo:evento');
    }
});

Where this.container is the #quiz element. This works half the time, but the rest of the time the target of the click event is one of the spans inside the button, so my event handler isn't called. What's the best way to deal with this situation?

解决方案

Alternate Solution:

MDN: Pointer events

Add a class to all nested child elements (.pointer-none)

.pointer-none {
  pointer-events: none;
}

Your mark-up becomes

<div id="quiz">
    <button id="game-again" class="game-again">
        <span class="icon-spinner icon pointer-none"></span>
        <span class="pointer-none">Go again</span>
    </button>
</div>

With the pointer set to none, the click event wouldn't fire on those elements.

https://css-tricks.com/slightly-careful-sub-elements-clickable-things/

这篇关于Vanilla JS 事件委托——处理目标元素的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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