如何节省 jquery 选择器

how to economize jquery selectors

可能是个愚蠢的问题,但我找不到直接的答案,那么如何将 ":not('#home div, .nav')" 更改为 ":not('this div, .nav')" 之类的内容?这将允许我为不同的对象重用相同的功能。

 $( "#home" ).click(function() {
     $("#content .plates").children(":not('#home div, .nav')" ).fadeOut(700);     
    });

如果需要,这里是 HTML:

<div id="wrapper">
 <div id="content">
  <div id="home" class="plates">
   <div class="nav"></div>
   <div id="one"></div>
   <div id="two"></div>
  </div>
  <div id="about" class="plates">
   <div class="nav"></div>
   <div id="three"></div>
   <div id="four"></div>
  </div>
 </div>
</div>

感谢您的帮助!

您正在使用 CSS selector :not(), but you can also use jQuery chained function .not(),它从另一组匹配元素中减去匹配元素。

用法是这样的:

$(selector1).not(selector2).fadeOut(700);

其中 selector2 中的元素将从与 selector1 匹配的集合中减去。

让我们从头开始。如果您遵循规范并且 ID 在您的页面上是唯一的(它们应该是唯一的),您的点击事件选择器应该只是

$("#home").click(function() {...});

此外,内部选择器应该是

$("#content .plates").children(...);

无需将 ID 选择器堆叠在其他 ID 选择器之前,因为 ID 应该是唯一的并且选择器是从右到左解析的。

您可以使用 jQuery not 来排除点击的元素。

代码:

$("#wrapper #content #home").click(function () {
    $("#wrapper #content .plates").children(':not(.nav)').not($(this)).fadeOut(700);
});

演示:http://jsfiddle.net/IrvinDominin/dms6u1ww/

在处理程序中,this 将是被点击的元素,因此您可以只使用:

$( "#home" ).click(function() {
   $("#wrapper #content .plates").children(":not('#"+this.id+" div, .nav')" ).fadeOut(700);     
 });
$("#wrapper #content #home" ).click(function() {
    $("#wrapper #content .plates").children().not($('div', this)).not('.nav').fadeOut(700);  
});

OP 要求一些通用的东西,可以在 "home" 和 "about" div 上重复使用(也许以后会添加到其他 div 上?)。但是,对于每一个,从淡出中排除 "nav" 项目。所以试试这个:

function myFunc( clickableItem) {
    $(".plates:not(" + clickableItem + ")").children( ":not('.nav')" ).fadeOut(700); }

$( "#home" ).click( function(){
    myFunc( "#home");
});

$( "#about" ).click( function(){
    myFunc("#about");
});