Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  189] [ 3]  / answers: 1 / hits: 47032  / 13 Years ago, thu, september 15, 2011, 12:00:00

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?


More From » jquery

 Answers
18

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
}
});

[#90087] Tuesday, September 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rey

Total Points: 415
Total Questions: 100
Total Answers: 100

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;