停止从子元素到父元素的事件转发
让我们假设有以下代码:
<body style="overflow: hidden">
<div class="wall">
<button>New</button>
<div class="prova">
<a href="localhost">ciao !</a>
</div>
<div class="prova">
<a href="localhost">miao !</a>
</div>
</div>
</body>
和以下 js/jquery 代码:
function onBoot()
{
$(".prova").draggable();
$(".wall").mousedown(onMouseDown);
$(".wall").mouseup(onMouseUp);
}
function onMouseDown(e)
{
console.log("down");
}
function onMouseUp(e)
{
console.log("up");
}
$(onBoot);
现在,我正确地看到了按钮和两个 div。 当我单击“wall”(父 div)时,我在控制台上看到了“向下”/“向上”,正如我所期望的那样。 但是,当我单击“prova”div 和按钮时,我也在控制台上看到“向下”/“向上”。 我知道“冒泡”概念,即事件从子元素转发到父元素,我想阻止它,但没有在“prova”div 上指定显式事件处理程序。 是否可以 ?
let's suppose to have following code:
<body style="overflow: hidden">
<div class="wall">
<button>New</button>
<div class="prova">
<a href="localhost">ciao !</a>
</div>
<div class="prova">
<a href="localhost">miao !</a>
</div>
</div>
</body>
and the following js/jquery code:
function onBoot()
{
$(".prova").draggable();
$(".wall").mousedown(onMouseDown);
$(".wall").mouseup(onMouseUp);
}
function onMouseDown(e)
{
console.log("down");
}
function onMouseUp(e)
{
console.log("up");
}
$(onBoot);
Now, I correctly see the button and the two divs.
When I click on "wall" (parent div) I see "down"/"up" on console as I expect.
However, I see "down"/"up" on console also when I click on "prova" divs and button too.
I know about "bubbling up" concept for which an event is forwarded from children to parent elements and I want to prevent it but without specifying an explicit event handler on "prova" divs.
Is it possible ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以检查发起者的 className,如下所示:
参见 this jsfiddle
You can check the originators className, like this:
see this jsfiddle
在事件处理程序(
OnMouseDown
、OnMouseUp
)中,检查e.currentTarget
是否等于e.target
。请参阅 jQuery 事件文档:因此,例如:
In your event handler (
OnMouseDown
,OnMouseUp
), check ife.currentTarget
equalse.target
. See jQuery Events documentation:So, for example: