简体   繁体   中英

how to economize jquery selectors

Probably a stupid question, but I couldn't find a direct answer, so how can I change ":not('#home div, .nav')" in to something like ":not('this div, .nav')" ? That would allow me reuse the same function for different objects.

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

and here is the HTML if needed:

<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>

Thanks for your help!

In the handler, this will be the clicked element, so you could just use this:

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

You are using CSS selector :not() , but you can also use jQuery chained function .not() , which subtracts matched elements from another set of matched elements.

The usage is like this:

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

Where elements in selector2 will get substracted from set matched by selector1 .

Let's start from the top. Provided you follow the spec and IDs are unique on your page (as they should be), your click event selector should be just

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

Also, the inner selector should be

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

There's no need to stack ID selectors in front of other ID selectors since IDs should be unique and selectors are parsed from right to left.

You can use jQuery not to exclude the clicked element.

Code:

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

Demo: http://jsfiddle.net/IrvinDominin/dms6u1ww/

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

The OP is asking for something generic that can be reused on both the "home" and the "about" divs (and maybe on others to be added later?). But, for each one, excluding the "nav" item from the fadeout. So try this:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM