如果条件为true,如何将类添加到jQuery元素,如果条件为false,则删除相同的类? [英] How to add class to a jQuery element if a condition is true and remove the same class if the condition is false?
本文介绍了如果条件为true,如何将类添加到jQuery元素,如果条件为false,则删除相同的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更短的方法来执行以下操作?
Is there a shorter way to do the following?
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
if (is_checked) {
select_all_checkbox.parent().addClass("selected");
} else {
select_all_checkbox.parent().removeClass("selected");
}
推荐答案
使用 toggleClass
,传递第二个参数(布尔值),指定是否应该添加类:
Use toggleClass
, passing a second argument (a boolean) that specifies whether the class should be added or not:
select_all_checkbox.parent().toggleClass("selected", is_checked);
如果你有多个元素被<$ c选中$ c> input.select_all ,你必须迭代它们:
$("input.select_all").each(function() {
$(this).parent().toggleClass('selected', this.checked);
});
这篇关于如果条件为true,如何将类添加到jQuery元素,如果条件为false,则删除相同的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文