[英]How to prevent event propagation on a <button /> element?
[英]Prevent propagation on inline event element?
这是我的小提琴:
https://jsfiddle.net/rpq6swu2/
<div id="container" onclick="alert('clicked in container')">
<div id="div1" >Something inside the other div</div>
</div>
// div1 is added dynamically normally inside the container.
$(document).on('click', '#container #div1', function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
alert('clicked in div1 only');
})
我无法修改 html 部分:它是由其他人完成的。
我过去自己也遇到过这个问题。 问题是“点击”是两个事件的合并: mousedown
和mouseup
。 只需将“click”更改为“mousedown”,它应该可以按预期工作,正如您在下面的代码段中所见(与您的代码相同,但有一个更改)。
$(document).on('mousedown', '#container #div1', function(e) { e.stopPropagation(); e.stopImmediatePropagation(); alert('clicked in div1 only'); })
#container { background-color: red; width: 640px; height: 640px; } #div1 { background-color: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container" onclick="alert('clicked in container')"> <div id="div1" >Something inside the other div</div> </div>
- - - 编辑 - - -
我想指出,我认为这个问题只是因为 jQuery.on() 的工作原理——我认为它对“点击”的理解与原生点击事件之间存在差异。
在这里阅读比我聪明得多的人的讨论:
https://github.com/jquery/jquery/issues/3693
因此,您可以只使用本机 javascript 事件处理程序并停止单击事件传播。 或者对两个 div 使用 jQuery 事件处理程序。 我认为这是导致问题的混合。
这是一个仅使用本机 javascript 的片段:
function onDiv1Click(e) { e.stopPropagation(); alert('div 1 clicked'); }
#container { background-color: red; width: 640px; height: 640px; } #div1 { background-color: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container" onclick="alert('clicked in container')"> <div id="div1" onclick="onDiv1Click(event)">Something inside the other div</div> </div>
在这里只使用 jQuery
$(document).on('click', '#container', function(e) { alert('clicked in container'); }) $(document).on('click', '#container #div1', function(e) { e.stopPropagation(); alert('clicked in div1 only'); });
#container { background-color: red; width: 640px; height: 640px; } #div1 { background-color: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> <div id="div1" >Something inside the other div</div> </div>
你看到这两个选项都有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.