我正在尝试使用vanilla JS进行事件委派。我在一个容器里有一个按钮,就像这样
<div id="quiz">
<button id="game-again" class="game-again">
<span class="icon-spinner icon"></span>
<span>Go again</span>
</button>
</div>
在David Walsh's nice instructions之后,我向按钮的祖先添加了一个事件处理程序,如下所示:
this.container.addEventListener('click', function(e){
if (e.target && e.target.id == 'game-again') {
e.stopPropagation();
self.publish('primo:evento');
}
});
其中this.container
是#quiz元素。这在一半的时间内是有效的,但在其余的时间里,click事件的目标是按钮内部的一个跨度,所以我的事件处理程序不会被调用。处理这种情况的最好方法是什么?
发布于 2019-04-11 08:43:18
替代解决方案:
向所有嵌套子元素添加类(.pointer-none
)
.pointer-none {
pointer-events: none;
}
您的标记将变为
<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>
当指针设置为none时,click事件将不会在这些元素上触发。
https://css-tricks.com/slightly-careful-sub-elements-clickable-things/
发布于 2014-06-09 09:39:24
较新的浏览器
较新的浏览器支持.matches
this.container.addEventListener('click', function(e){
if (e.target.matches('#game-again,#game-again *')) {
e.stopPropagation();
self.publish('primo:evento');
}
});
您可以使用以下命令获取无前缀的版本
var matches = document.body.matchesSelector || document.body.webkitMatchesSelector || document.body.mozMatchesSelector || document.body.msMatchesSelector || document.body.webkitMatchesSelector
然后在更多的浏览器上使用.apply
(仍然是IE9+)。
较旧的浏览器
假设您必须支持较旧的浏览器,您可以遍历DOM:
function hasInParents(el,id){
if(el.id === id) return true; // the element
if(el.parentNode) return hasInParents(el.parentNode,id); // a parent
return false; // not the element nor its parents
}
然而,这将攀登整个dom,并且您希望在委托目标处停止:
function hasInParentsUntil(el,id,limit){
if(el.id === id) return true; // the element
if(el === limit) return false;
if(element.parentNode) return hasInParents(el.parentNode,id); // a parent
return false; // not the element nor its parents
}
这将使您的代码:
this.container.addEventListener('click', function(e){
if (hasInParentsUntil(e.target,'game-again',container)) { // container should be
e.stopPropagation(); // available for this
self.publish('primo:evento');
}
});
https://stackoverflow.com/questions/24117369
复制相似问题