问题
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\")
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.
回答1:
Try using the not() method instead of the :not() selector.
$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
回答2:
You can use the not function rather than the :not selector:
$(".content a").not(this).hide("slow")
回答3:
You can also use the jQuery .siblings()
method:
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');
});
Working demo: http://jsfiddle.net/wTm5f/
回答4:
You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:
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');
});
See here: http://jsfiddle.net/3bzLV/1/
来源:https://stackoverflow.com/questions/437958/how-can-i-exclude-this-from-a-jquery-selector