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

后端 未结 2 555
自闭症患者
自闭症患者 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);
    });
    
    0 讨论(0)
  • 2021-01-11 10:03

    Absolutely! You can choose between the methods (addClass/removeClass) programmatically, and use the one that is returned when an expression is executed.

    Like this:

    var select_all_checkbox = $("input.select_all");
    var is_checked = select_all_checkbox.prop("checked");
    
    select_all_checkbox.parent()[is_checked ? "addClass" : "removeClass"]("selected");
    
    0 讨论(0)
提交回复
热议问题