I'm trying to figure out how to do a switch statement where I need to find a class name of the object, then do something depending on the class name (in the switch statement).
In this example, I need the switch statement to do whatever I need when the class contains a specific word, such as "person".
html
<div class="person temp something"></div>
javascript
$(document).on('mousedown', function(e) {
var clicked = $(e.target).attr('class');
console.log(clicked);
switch (clicked) {
case "person":
//do something
break;
default:
//do something
}
});
It's not guaranteed that the switch statement name, such as "person" will be in the first spot.
I know I can search through an array for a specific word, but I don't know how to add that to this sort of thing.
As I said in my comment, a switch
statement doesn't appear the appropriate approach in this situation.
Since you are using jQuery, just use .hasClass
:
if ($(e.target).hasClass('person')) {
// do something
}
If you want to do something more complicated for multiple classes, you can create a class -> function
mapping and simply iterate over the class list:
var classActions = {
person: function(element) { /* do something */ },
temp: function(element) { /* do something */},
// ...
};
var classes = e.target.className.split(/\s+/);
$.each(classes, function(index, cls) {
classActions[cls](e.target);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With