[英]How do I prevent parent event handler on a child node?
I have a div and it's listend by a event handler:我有一个 div,它被一个事件处理程序监听:
$('.thediv').click(function() { $(this).remove() });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="width:500px;height:500px"> <input type="input" style="width:100px;height:20px" /> </div>
The div would be removed if it's clicked.如果单击该 div,它将被删除。
However, I want to put a text input box on the div and if the user clicks the text input, the div should not be removed.但是,我想在 div 上放置一个文本输入框,如果用户单击文本输入,则不应删除 div。 Only when the user clicks the area outside the input box, the div get removed.
只有当用户点击输入框外的区域时,div 才会被移除。
What can I do?我能做什么?
Only remove if the target of the event does not match input
:仅当事件的目标与
input
不匹配时才删除:
$('.thediv').click(function(e) { if (!e.target.matches('input')) { $(this).remove(); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="thediv" style="width:500px;height:500px"> other div content <input style="width:100px;height:20px"> </div>
on input click use .stopPropagation() this will prevent from call the parent click在输入点击使用.stopPropagation()这将阻止调用父点击
$('.thediv').click(function(){$(this).remove()}); $('#input').click(function(e) { e.stopPropagation(); });
<div class="thediv" style=""> <input type="input" id="input" /><br /> text here <h1>text here </h1> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In the following demo:在以下演示中:
.box
is the parent element that listens for the click event. .box
是监听点击事件的父元素。.box
is also referred to as event.currentTarget
because it is registered to the click event. .box
也称为event.currentTarget
因为它已注册到单击事件。.box
is also considered this
within the callback function. .box
在回调函数中也被认为是this
。event.target
is the origin of the event -- the element that the user clicked. event.target
是事件的来源——用户点击的元素。.box
has an <input>
child element. .box
有一个<input>
子元素。if the clicked element (aka
event.target
-- see #4)如果被点击的元素(又名
event.target
-- 见 #4)
isthis
(aka.box
-- see #3), then...this
是(又名.box
见#3),然后......
removethis
删除
this
Note: This will exclude anything within .box
that is clicked not just an <input>
.注意:这将排除
.box
中被点击的任何.box
,而不仅仅是<input>
。
$('.box').click(function(event) { if (this === event.target) { $(this).remove(); } });
<fieldset class='box' style="width:500px;height:500px"> <input type="text" style="width:100px;height:20px"> </fieldset> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.