How to add class to a jQuery element if a condition is true and remove the same class if the condition is false?

后端 未结 2 743
自闭症患者
自闭症患者 2021-01-11 09:16

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


        
2条回答
  •  感动是毒
    2021-01-11 10:01

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

    If you have multiple elements selected by input.select_all, you have to iterate over them though:

    $("input.select_all").each(function() {
        $(this).parent().toggleClass('selected', this.checked);
    });
    

提交回复
热议问题