试图绕过jQuery".not()"函数,并遇到问题.我希望父div可以"可点击"但如果用户点击子元素,则不会调用该脚本.
$(this).not(children()).click(function(){
$(".example").fadeOut("fast");
});
Run Code Online (Sandbox Code Playgroud)
html:
<div class="example">
<div>
<p>This content is not affected by clicks.</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Nic*_*ver 193
为此,请使用.stopPropagation停止对子项的单击:
$(".example").click(function(){
$(this).fadeOut("fast");
}).children().click(function(e) {
return false;
});
Run Code Online (Sandbox Code Playgroud)
这将阻止孩子点击冒泡超过他们的水平,这样父母就不会收到点击.
.not() 使用方式稍有不同,它会过滤选择器中的元素,例如:
<div class="bob" id="myID"></div>
<div class="bob"></div>
$(".bob").not("#myID"); //removes the element with myID
Run Code Online (Sandbox Code Playgroud)
对于点击,您的问题是点击儿童会冒泡到父母,而不是您无意中将点击处理程序附加到孩子.
Mat*_*rey 174
我正在使用以下标记并遇到了同样的问题:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这里我使用了以下逻辑:
$(".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");
});
Run Code Online (Sandbox Code Playgroud)
就确切的问题而言,我可以看到其工作如下:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
Run Code Online (Sandbox Code Playgroud)
或者反过来说:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
dan*_*i24 21
或者你也可以这样做:
$('.example').on('click', function(e) {
if( e.target != this )
return false;
// ... //
});
Run Code Online (Sandbox Code Playgroud)
小智 8
我的解决方案:
jQuery('.foo').on('click',function(event){
if ( !jQuery(event.target).is('.foo *') ) {
// code goes here
}
});
Run Code Online (Sandbox Code Playgroud)
小智 6
我个人会向子元素添加一个点击处理程序,它只会停止点击的传播。所以它看起来像:
$('.example > div').click(function (e) {
e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107817 次 |
| 最近记录: |