Answers:
为此,请使用.stopPropagation停止对子级的点击:
$(".example").click(function(){
$(this).fadeOut("fast");
}).children().click(function(e) {
return false;
});
这样可以阻止孩子的点击次数超过其水平,从而使父级不会收到该点击。
.not() 用法有所不同,它从选择器中过滤出元素,例如:
<div class="bob" id="myID"></div>
<div class="bob"></div>
$(".bob").not("#myID"); //removes the element with myID
e.stopPropagation();代替return false;。
}).find('.classes-to-ignore').click(function(e) {用来选择特定的子元素
e.stopPropagation()然后再使用return false。return false等价于此,e.preventDefault(); e.stopPropagation()因此可能会有意想不到的副作用。
我正在使用以下标记,并且遇到了同样的问题:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
在这里,我使用了以下逻辑:
$(".nav > li").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
// this section only processes if the .nav > li itself is clicked.
alert("you clicked .nav > li, but not it's children");
});
关于确切的问题,我可以看到它的工作方式如下:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
或者当然也可以:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
希望有帮助。
或者,您也可以:
$('.example').on('click', function(e) {
if( e.target != this )
return false;
// ... //
});
我的解决方案:
jQuery('.foo').on('click',function(event){
if ( !jQuery(event.target).is('.foo *') ) {
// code goes here
}
});
我个人会向子元素添加一个点击处理程序,该操作除了停止点击的传播外什么也没有做。因此,它看起来像:
$('.example > div').click(function (e) {
e.stopPropagation();
});
stopPropagation和其他答案一样,返回false和有什么区别?
stopPropagation更干净,因为它不会阻止发生在上的子元素上的事件return false。
这是一个例子。绿色正方形是父元素,黄色正方形是子元素。
希望这会有所帮助。
var childElementClicked;
$("#parentElement").click(function(){
$("#childElement").click(function(){
childElementClicked = true;
});
if( childElementClicked != true ) {
// It is clicked on parent but not on child.
// Now do some action that you want.
alert('Clicked on parent');
}else{
alert('Clicked on child');
}
childElementClicked = false;
});
#parentElement{
width:200px;
height:200px;
background-color:green;
position:relative;
}
#childElement{
margin-top:50px;
margin-left:50px;
width:100px;
height:100px;
background-color:yellow;
position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parentElement">
<div id="childElement">
</div>
</div>