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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/437958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:09:01  来源:igfitidea点击:

How can I exclude $(this) from a jQuery selector?

jqueryjquery-selectorsthis

提问by Logan Serman

I have something like this:

我有这样的事情:

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

When one of these links is clicked, I want to perform the .hide() function on the links that are not clicked. I understand jQuery has the :not selector, but I can't figure out how to use it in this case because it is necessary that I select the links using $(".content a")

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

I want to do something like

我想做类似的事情

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

but I can't figure out how to use the :not selector properly in this case.

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

回答by Dan Herbert

Try using the not()methodinstead of the :not()selector.

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

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

回答by Zach Langley

You can use the notfunction rather than the :notselector:

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

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

回答by Edgar Ortega

You can also use the jQuery .siblings()method:

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

HTML

HTML

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

Javascript

Javascript

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

Working demo: http://jsfiddle.net/wTm5f/

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

回答by Ronen Cypis

You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:

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

HTML

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

CSS

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

Javascript

Javascript

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

See here: http://jsfiddle.net/3bzLV/1/

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