开发者

Can I write this JQuery statement cleaner?

开发者 https://www.devze.com 2022-12-24 08:17 出处:网络
So I have the following: var box = $(\".MyCheckBox\"); if (box[0].checked) { // Do something } else { // Do someth开发者_JS百科ing else

So I have the following:

var box = $(".MyCheckBox");

if (box[0].checked)
{
    // Do something
}
else
{
    // Do someth开发者_JS百科ing else
}

Is there a better way of doing this using filters or something?

I know I can go:

$(".MyCheckBox")
    .filter(function(index) {
         return this.checked;
     })
    .each(function() {
         // do something
     });

But I need to do something in the else statement... easier way of doing this? Thanks!


You can use the built-in :checked selector:

$(".MyCheckBox:checked").each(function() {
  //Do something with checked ones..
});
$(".MyCheckBox:not(:checked)").each(function() {
  //Do something with unchecked ones..
});

Or filter in the each similar to what you have:

$(".MyCheckBox").each(function() {
  if($(this).is(":checked")) {
    //Do something with checked ones..
  } else {
    //Do something with unchecked ones..
  }
});

Or if say you wanted to toggle a class, then use a different approach, this would give the active class to the checked ones:

$(".MyCheckBox").each(function() {
  $(this).toggleClass("active", $(this).is(":checked"));
});

Update
Based on comments if you want just raw speed:

$(".MyCheckBox").each(function() {
  if(this.checked) {
    //Do something with checked ones..
  } else {
    //Do something with unchecked ones..
  }
});


attr('checked') returns the checked value of the first element anyway, so no [0] malarky.

if ($(".MyCheckBox").attr('checked')) {
 // Do something
} else {
 // else
}


I'd go with Nick's updated answer above, but would like to suggest that you complete your selector. i.e.,

$('input.myCheckBox').each(function(){
    // tralalala...
}

... just for the fact that it makes your initial jQuery selection a bit faster. I mean, since we're debating about speed and all. ^_^

0

精彩评论

暂无评论...
验证码 换一张
取 消