所以我有以下内容:
var box = $(".MyCheckBox");
if (box[0].checked)
{
// Do something
}
else
{
// Do something else
}
有没有更好的方法使用过滤器或其他东西来做到这一点?
我知道我可以去:
$(".MyCheckBox")
.filter(function(index) {
return this.checked;
})
.each(function() {
// do something
});
但是我需要在 else 语句中做一些事情……更简单的方法吗?谢谢!
最佳答案
您可以使用内置的 :checked
选择器:
$(".MyCheckBox:checked").each(function() {
//Do something with checked ones..
});
$(".MyCheckBox:not(:checked)").each(function() {
//Do something with unchecked ones..
});
或在每个与您所拥有的相似的项中进行过滤:
$(".MyCheckBox").each(function() {
if($(this).is(":checked")) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
或者如果说您想切换一个类,然后使用不同的方法,这会将 active
类提供给选中的类:
$(".MyCheckBox").each(function() {
$(this).toggleClass("active", $(this).is(":checked"));
});
更新
如果您只想要原始速度,请根据评论:
$(".MyCheckBox").each(function() {
if(this.checked) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
关于javascript - 我可以把这个 JQuery 语句写得更干净吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541320/