JQuery .hasClass for multiple values in an if statement

后端 未结 10 786
名媛妹妹
名媛妹妹 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:31

    This may be another solution:

    if ($('html').attr('class').match(/m320|m768/)) {  
      // do stuff   
    }  
    

    according to jsperf.com it's quite fast, too.

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

    For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:

    $.fn.hasAnyClass = function() {
        for (var i = 0; i < arguments.length; i++) {
            if (this.hasClass(arguments[i])) {
                return true;
            }
        }
        return false;
    }
    

    Then, in your example, you could use this:

    if ($('html').hasAnyClass('m320', 'm768')) {
    
    // do stuff 
    
    }
    

    You can pass as many class names as you want.


    Here's an enhanced version that also lets you pass multiple class names separated by a space:

    $.fn.hasAnyClass = function() {
        for (var i = 0; i < arguments.length; i++) {
            var classes = arguments[i].split(" ");
            for (var j = 0; j < classes.length; j++) {
                if (this.hasClass(classes[j])) {
                    return true;
                }
            }
        }
        return false;
    }
    
    if ($('html').hasAnyClass('m320 m768')) {
        // do stuff 
    }
    

    Working demo: http://jsfiddle.net/jfriend00/uvtSA/

    0 讨论(0)
  • 2020-12-02 18:32
    var classes = $('html')[0].className;
    
    if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
        //do something
    }
    
    0 讨论(0)
  • 2020-12-02 18:33

    You could use is() instead of hasClass():

    if ($('html').is('.m320, .m768')) { ... }
    
    0 讨论(0)
  • 2020-12-02 18:39

    Try this:

    if ($('html').hasClass('class1 class2')) {
    
    // do stuff 
    
    }
    
    0 讨论(0)
  • 2020-12-02 18:44

    Here is a slight variation on answer offered by jfriend00:

    $.fn.hasAnyClass = function() {
        var classes = arguments[0].split(" ");
        for (var i = 0; i < classes.length; i++) {
            if (this.hasClass(classes[i])) {
                return true;
            }
        }
        return false;
    }
    

    Allows use of same syntax as .addClass() and .removeClass(). e.g., .hasAnyClass('m320 m768') Needs bulletproofing, of course, as it assumes at least one argument.

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