jQuery:点击功能排除孩子.

sup*_*led 136 jquery

试图绕过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)

对于点击,您的问题是点击儿童会冒泡到父母,而不是您无意中将点击处理程序附加到孩子.

  • @Asaf - 使用`e.stopPropagation();`代替`return false;`用于那种情况. (18认同)
  • 我不明白为什么你告诉他使用`e.stopPropagation()`然后使用`return false`代替.`return false`相当于`e.preventDefault(); e.stopPropagation()`因此它可能会产生意想不到的副作用. (4认同)
  • 你也可以使用`}).find('.classes-to-ignore').click(function(e){`选择特定的子元素 (2认同)

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)

希望有所帮助.

  • 我认为这是更好的解决方案.它不会以任何方式干扰孩子,它应该表现得更好,因为如果有成千上万的孩子,它不会记录成千上万的回调. (28认同)
  • @ l2aelba - 你应该在jQuery的最新版本中使用`.on("click",...)`因为`.live()`自v1.7以来已被弃用.见http://api.jquery.com/live/ (4认同)
  • 这个答案比接受的答案更好,因为它不会中断子元素上的任何点击事件 (2认同)

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)

  • 感谢您的澄清。看起来“stopPropagation”可能更干净,因为它不会阻止子元素上的事件发生,而“return false”可能会发生这种情况。 (2认同)