简体   繁体   中英

jQuery one class name with multiple selectors

My coding is working fine, just wondered if there is more tidy way to write jQuery code? I was searching for this internet but cant find examples.

There are three duplicated class name with different selectors having different CSS settings. I would like to know if there is clean coding for this.

if ($(this).hasClass('toggle')) {


    $(".toggle > span:first").css({
        // something...
    });

    $(".toggle > span:nth-child(2)").css({
        // something...
    });

    $(".toggle > span:last").css({
        // something...
    });

}

Is there similar to SCSS way? Like below

.toggle {
    span {
        &:first-child { // something... }
        &:nth-child(2) { // something... }
        &:last-child { // something... }
    }
}

Thank you for taking time to look into this.

You can use .end()

$(".toggle")
.children("span:first").css({"color":"blue"})
.end()
.children("span:nth-child(2)").css({"color": "green"})
.end()
.children("span:last").css({"color": "red"});

Or, use .filter()

$(".toggle")
.children("span")
.filter(":first").css({"color":"blue"})
.end()
.filter(":nth-child(2)").css({"color": "green"})
.end()
.filter(":last").css({"color": "red"});
if ($(this).hasClass('toggle')) {

    $('.toggle > span')
        .first().css({
            // something...
        })
        .end().eq(2).css({
            // something...
        })
        end().last().css({
            // something...
        });

}

You can iterate through on them:

var i = 0;
$(".toggle span").each(function($obj) {
   console.log('Now i is ' + i);
   console.log($obj);
   switch (i) {
      case 0:
        //do something
        break;
        //and so on, or call a function with obj and i.
   }

   i++;
});

You can also add data-id or data-anything to your classes.

No, it`s not similar.

if ($(this).hasClass('toggle')) {    

    $(".toggle > span:first").css({
        // something...
    });

    $(".toggle > span:nth-child(2)").css({
        // something...
    });

    $(".toggle > span:last").css({
        // something...
    });

}

is similar to:

.toggle {
    > span {
        &:first-child { // something... }
        &:nth-child(2) { // something... }
        &:last-child { // something... }
    }
}

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