Reputation: 6622
If I have the following code,
$(".selector1, .selector2, .selector3").click(function() {
switch(CURRENT SELECTOR) {
}
});
I need the current selector inside for a switch statement, such as "selector1", "selector2". The selector option in jQuery is deprecated so that can not be used. I am also using jquery 1.4.2 so please try to keep it under that.
Upvotes: 1
Views: 282
Reputation: 11302
Use attr function to get the class value of clicked element:
$(".selector1, .selector2, .selector3").click(function() {
var elem_class = $(this).attr("class");
switch(elem_class) {
}
});
If elements have more than one class you can do:
$(".selector1, .selector2, .selector3").click(function() {
var arr = ["selector1", "selector2", "selector3"];
var arr2 = $(this).attr("class").split(" ");
var choosen_one = false;
for(var i=0; i<arr.length; i++) {
for(var j=0; j<arr.length; j++) {
if(arr[i] === arr2[j]) {
choosen_one = arr2[j];
break;
}
}
if(choosen_one) {
break;
}
}
switch(choosen_one) {
}
});
Reference:
Upvotes: 3
Reputation: 8697
Here are four ways to handle your issue:
1) class if you have just one per element:
$(".selector1, .selector2, .selector3").click(function() {
switch($(this).attr("class")) {
}
});
2) unique IDs not good, if you'd like to use it multiple times
$("#selector1, #selector2, #selector3").click(function() {
switch($(this).attr("id")) {
}
});
3) unique selector
$("[data-selector=selector1], [data-selector=selector2], [data-selector=selector3]").click(function() {
switch($(this).data("selector")) {
}
});
4) multiple event handlers:
$(".selector1").click(function() {
myFunction($(this));
});
$(".selector2").click(function() {
myFunction($(this));
});
$(".selector3").click(function() {
myFunction($(this));
});
function myFunction(myThis) {
//
}
Upvotes: 0
Reputation: 9262
If you're using jQuery 1.4.2, why can't you use the .selector
property? It wasn't deprecated until 1.7.
Upvotes: 0