如何从jQuery选择器中排除$(this)?

Log*_*man 200 jquery this jquery-selectors

我有这样的事情:

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>
Run Code Online (Sandbox Code Playgroud)

单击其中一个链接时,我想在未单击的链接上执行.hide()函数.我理解jQuery有:not selector,但在这种情况下我无法弄清楚如何使用它因为我必须使用它来选择链接$(".content a")

我想做点什么

$(".content a").click(function()
{
    $(".content a:not(this)").hide("slow");
});
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我无法弄清楚如何正确使用:not selector.

Dan*_*ert 380

尝试使用该not() 方法而不是:not()选择器.

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});
Run Code Online (Sandbox Code Playgroud)

  • @marck没有上下文,我不知道.创建一个新问题,我也许可以提供帮助. (4认同)
  • 这是一个非常糟糕的解决方案(性能方面).没有真正的理由在'click`回调中`$(".content a")`在每次点击... (2认同)

Zac*_*ley 41

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

$(".content a").not(this).hide("slow")
Run Code Online (Sandbox Code Playgroud)


Edg*_*ega 9

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

HTML

<div class="content">
  <a href="#">A</a>
  <a href="#">B</a>
  <a href="#">C</a>
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

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

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


Ron*_*pis 5

您应该使用"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>
Run Code Online (Sandbox Code Playgroud)

CSS

.content {
    background-color:red;
    margin:10px;
}
.content.other {
    background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript

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

见这里:http://jsfiddle.net/3bzLV/1/