如何在 jQuery/Javascript 中编写 switch 语句来测试元素是否具有特定的类?
这是我正在使用的 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
}
});
已经有相当多的情况了,我认为使用 switch 语句会更简洁。我如何在 jQuery/javascript 中做到这一点?
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
}
});
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
试试这个。不太干净,但仍然是一个 switch 语句。
Try this. Not much cleaner, but still a switch statement.
问题是一个用户可能拥有多个类。否则你可以这样做:
The problem is that an user could have more than one class. Otherwise you could do:
我认为最干净的方法可能就是这样:
如果您有无数个对象,您甚至可以将它们放入这样的数据结构中:
既然您(在评论中)询问了如何为对象执行事件处理程序没有类名,如果您正在寻找没有类名,那么您可以这样做:
我在这里测试了它:http://jsfiddle.net/jfriend00/TAjKR/
I think the cleanest way might just be this:
If you had a zillion of them, you could even put them in a data structure like this:
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:
I tested it out here: http://jsfiddle.net/jfriend00/TAjKR/
我认为单个 switch 语句在这里没有帮助,因为一个元素可以有多个类,并且您不能使用 elem.className 进行切换。一种选择是以更具可读性的方式构建代码,使用 for 语句,其中包含开关...:
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 语句中的 hasClass:
To check hasClass in an switch statement:
我知道这已经晚了,您的用户只有一门课程,但是,如果有多个课程:
I know this is late and your user only has one class, but, if there was more than one class: