JQuery .hasClass for multiple values in an if statement

后端 未结 10 787
名媛妹妹
名媛妹妹 2020-12-02 18:14

I have a simple if statement as such:

if ($(\'html\').hasClass(\'m320\')) {

// do stuff 

}

This works as expected. However, I want to add

相关标签:
10条回答
  • 2020-12-02 18:44

    The hasClass method will accept an array of class names as an argument, you can do something like this:

    $(document).ready(function() {
    function filterFilesList() {
        var rows = $('.file-row');
        var checked = $("#filterControls :checkbox:checked");
    
        if (checked.length) {
            var criteriaCollection = [];
    
            checked.each(function() {
                criteriaCollection.push($(this).val());
            });
    
            rows.each(function() {
                var row = $(this);
                var rowMatch = row.hasClass(criteriaCollection);
    
                if (rowMatch) {
                    row.show();
                } else {
                    row.hide(200);
                }
            });
        } else {
            rows.each(function() {
                $(this).show();
            });
        }
    }
    
        $("#filterControls :checkbox").click(filterFilesList);
        filterFilesList();
    });
    
    0 讨论(0)
  • 2020-12-02 18:45

    You just had some messed up parentheses in your 2nd attempt.

    var $html = $("html");
    
    if ($html.hasClass('m320') || $html.hasClass('m768')) {
    
      // do stuff 
    
    }
    
    0 讨论(0)
  • 2020-12-02 18:49

    For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

    In short, using element.hasClass('class') is the fastest.

    Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

    The worst performance by far was using element.is('.class').

    Also listed in the jsperf is CyberMonk's function, and Kolja's solution.

    0 讨论(0)
  • 2020-12-02 18:49

    This is in case you need both classes present. For either or logic just use ||

    $('el').hasClass('first-class') || $('el').hasClass('second-class')
    

    Feel free to optimize as needed

    0 讨论(0)
提交回复
热议问题