【问题标题】:How can I exclude $(this) from a jQuery selector?如何从 jQuery 选择器中排除 $(this)?
【发布时间】:2010-10-01 01:53:14
【问题描述】:

我有这样的事情:

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>

当单击这些链接之一时,我想对未单击的链接执行 .hide() 函数。我知道 jQuery 有 :not 选择器,但我不知道在这种情况下如何使用它,因为 我必须使用 $(".content a")

选择链接

我想做类似的事情

$(".content a").click(function()
{
    $(".content a:not(this)").hide("slow");
});

但我不知道在这种情况下如何正确使用 :not 选择器。

【问题讨论】:

  • 尝试!$(this) 以获得更简单的代码。

标签: jquery jquery-selectors this


【解决方案1】:

尝试使用not() method 而不是:not() selector。

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});

【讨论】:

  • 为什么我不能让它工作... $("#menu-holder #first_level li").not(this).addClass("returnToParent");
  • @marck 没有上下文,我不知道。创建一个新问题,我也许可以提供帮助。
  • 这是一个非常糟糕的解决方案(性能方面)。没有真正的理由在 click 回调中使用 $(".content a")... 每次点击...
【解决方案2】:

您可以使用not 函数而不是:not 选择器:

$(".content a").not(this).hide("slow")

【讨论】:

    【解决方案3】:

    您也可以使用 jQuery .siblings() 方法:

    HTML

    <div class="content">
      <a href="#">A</a>
      <a href="#">B</a>
      <a href="#">C</a>
    </div>
    

    Javascript

    $(".content").on('click', 'a', function(e) {
      e.preventDefault();
      $(this).siblings().hide('slow');
    });
    

    工作演示:http://jsfiddle.net/wTm5f/

    【讨论】:

      【解决方案4】:

      您应该使用“siblings()”方法,并防止为了应用该效果而一遍又一遍地运行“.content a”选择器:

      HTML

      <div class="content">
          <a href="#">A</a>
      </div>
      <div class="content">
          <a href="#">B</a>
      </div>
      <div class="content">
          <a href="#">C</a>
      </div>
      

      CSS

      .content {
          background-color:red;
          margin:10px;
      }
      .content.other {
          background-color:yellow;
      }
      

      Javascript

      $(".content a").click(function() {
        var current = $(this).parent();
        current.removeClass('other')
          .siblings()
          .addClass('other');
      });
      

      请看这里:http://jsfiddle.net/3bzLV/1/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 2011-01-28
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多