如何从 jQuery 选择器中排除 $(this)?
-
22-07-2019 - |
题
我有这样的事情:
<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 选择器。
解决方案
尝试使用 not()
方法 而不是 :not()
选择器.
$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
其他提示
您还可以使用的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');
});
您应该使用“的兄弟姐妹()”的方法,并且从运行只是用于施加作用一遍一遍“内容是”选择器防止:
<强> 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/
不隶属于 StackOverflow