如何在jQuery / Javascript中编写一个switch语句来测试一个元素是否有特定的类? [英] How to write a switch statement in jQuery/Javascript to test if an element has a particular class?
本文介绍了如何在jQuery / Javascript中编写一个switch语句来测试一个元素是否有特定的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我使用的if-else语句的结构:
This is the structure of the if-else statement I am using:
$('.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
}
});
有相当多的情况已经和我认为使用switch语句会更整洁。如何在jQuery / javascript中执行它?
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?
推荐答案
问题是用户可能有多个类。否则你可以这样做:
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
}
});
这篇关于如何在jQuery / Javascript中编写一个switch语句来测试一个元素是否有特定的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文