如何在 jQuery/Javascript 中编写 switch 语句来测试元素是否具有特定类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7433409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:14:47  来源:igfitidea点击:

How to write a switch statement in jQuery/Javascript to test if an element has a particular class?

javascriptjqueryclassif-statementswitch-statement

提问by catandmouse

This is the structure of the if-else statement I am using:

这是我使用的 if-else 语句的结构:

$('.myclass a').click(function() {
   if ($(this).hasClass('class1')) {
        //do something
   } else if ($(this).hasClass('class2')) {
        //do something
   } else if ($(this).hasClass('class3')) {
        //do something
   } else if ($(this).hasClass('class4')) {
        //do something
   } else {
        //do something
   }
});

There are quite a number of cases already and I thought using a switch statement would be neater. How do I do it in jQuery/javascript?

已经有很多情况了,我认为使用 switch 语句会更简洁。我如何在 jQuery/javascript 中做到这一点?

回答by Xyan Ewing

Try this. Not much cleaner, but still a switch statement.

尝试这个。没有更干净,但仍然是一个 switch 语句。

$('.myclass a').click(function() {
    switch (true) {
      case $(this).hasClass('class1'):
        // do stuff
        break;
      case $(this).hasClass('class2'):
        // do stuff
        break;
      case $(this).hasClass('class3'):
        // do stuff
        break;
    }
}

回答by Nicola Peluchetti

The problem is that an user could have more than one class. Otherwise you could do:

问题是一个用户可能有多个类。否则你可以这样做:

$('.myclass a').click(function() {
   var className = $(this).attr('class');
   switch(className){
      case 'class1':
     //put your cases here
   }
});

回答by jfriend00

I think the cleanest way might just be this:

我认为最干净的方法可能就是这样:

$('.myclass a.class1').click(function() {
   // code to process class1
});

$('.myclass a.class2').click(function() {
   // code to process class2
});

$('.myclass a.class3').click(function() {
   // code to process class3
});

$('.myclass a.class4').click(function() {
   // code to process class4
});

If you had a zillion of them, you could even put them in a data structure like this:

如果你有无数个,你甚至可以把它们放在这样的数据结构中:

// to define them all
var classHandlers = {
    class1: function() {
        // class1 code here
    },
    class2: function() {
        // class2 code here
    },
    class3: function() {
        // class3 code here
    },
    class4: function() {
        // class4 code here
    }
};

// to register them all
$.each(classHandlers, function(key, fn) {
    $('.myclass a.' + key).click(fn);
});

Since you've asked (in a comment) how you would do an event handler for the objects with no class name, here's how you could do that if you were looking for no class name:

由于您已经询问(在评论中)您将如何为没有类名的对象执行事件处理程序,因此如果您不寻找类名,您可以这样做:

$(".myclass a").not("[class]").click(function() {
    // code to handle objects with no class name here
});

I tested it out here: http://jsfiddle.net/jfriend00/TAjKR/

我在这里测试了它:http: //jsfiddle.net/jfriend00/TAjKR/

回答by Sayed Shahidi

To check hasClass in an switch statement:

在 switch 语句中检查 hasClass:

var elementClass;
var classCheck = $('#myElement').hasClass(elementClass)

switch(classCheck){
  case elementClass === 'foo':
     console.log('whatever');
     break;
}

回答by 4lackof

I know this is late and your user only has one class, but, if there was more than one class:

我知道这已经晚了,您的用户只有一门课,但是,如果有不止一门课:

//<div class="foo bar"></div>
//<div class="other bar"></div>

switch(true) {
  case 'foo':
    true;
    break;
  case 'other':
    true;
}

回答by Mr. HK

    $("#isTest").click(function () {

   if($('div').is('.redColor')){
    $('div').addClass('blueColor');
   }

    });

    $("#hasClassTest").click(function () {

   if($('div').hasClass('.redColor')){
    $('div').addClass('blueColor');
   }

    });

 $("#reset").click(function () {
   location.reload();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<style type="text/css">
  .redColor {
   background:red;
  }
  .blueColor {
   background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery check if an element has a certain class</h1>

  <div class="redColor">This is a div tag with class name of "redColor"</div>

  <p>
  <button id="isTest">is('.redColor')</button>
  <button id="hasClassTest">hasClass('.redColor')</button>
  <button id="reset">reset</button>
  </p>

</body>
</html>

回答by Alex Pacurar

I do not think that a single switch statement will help here, because one element can have multiple classes, and you cannot use elem.className to switch. An option is to structure the code in a more readable way, using a for statement in which to have switches...:

我认为单个 switch 语句在这里没有帮助,因为一个元素可以有多个类,并且您不能使用 elem.className 进行切换。一种选择是以更具可读性的方式构建代码,使用 for 语句在其中具有开关...:

$('.myclass a').click(function() 
{
    var classes = ["class1", "class2", "class3","class4"];
    var self = $(this);
    for(var i =0, ii = classes.length;i<ii;i++)
    {
        var className = classes[i];
        if(self.hasClass(className))
        {
            switch(className)
            {
                case 'class1':
                    //code here... 
                break;
                case 'class2':
                    //code here... 
                break;      
                case 'class3':
                    //code here... 
                break;     
                case 'class4':
                    //code here... 
                break;
            }

        }
    }       
});