代码之家  ›  专栏  ›  技术社区  ›  superUntitled

jquery:点击功能排除子项。

  •  124
  • superUntitled  · 技术社区  · 14 年前

    尝试用jquery“.not()”函数来包装我的头,然后遇到了一个问题。我希望父DIV是“可单击的”,但如果用户单击子元素,则不会调用脚本。

    $(this).not(children()).click(function(){
       $(".example").fadeOut("fast");
    });
    

    HTML:

    <div class="example">
       <div>
          <p>This content is not affected by clicks.</p>
       </div>
    </div>
    
    4 回复  |  直到 6 年前
        1
  •  184
  •   Evan Nagle    12 年前

    要执行此操作,请停止单击子项 using .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
    

    对于单击,您的问题是 click on a child bubbles up to the parent ,而不是您无意中将单击处理程序附加到子级。

        2
  •  165
  •   MatCarey    10 年前

    我正在使用以下标记,遇到了相同的问题:

    <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");
       }
    });
    

    希望有帮助。

        3
  •  18
  •   dani24    8 年前

    或者你也可以这样做:

    $('.example').on('click', function(e) { 
       if( e.target != this ) 
           return false;
    
       // ... //
    });
    
        4
  •  2
  •   npl len    6 年前

    我的解决方案:

    jQuery('.foo').on('click',function(event){
        if ( !jQuery(event.target).is('.foo *') ) {
            // code goes here
        } 
    });