Reputation: 6334
I have 3 different groups of divs that all handle different menu selections. Let's suppose that one is wrapped in class="class1", another is wrapped in class="class2", etc.
These classes would also be exclusive of each other.
Then suppose I have code:
$('.class1, .class2, .class3').click(function(e){
//which class was it that triggered this event?
});
Is it possible to find this out? I suppose I can use hasClass() for each instance, or this.className - but in the latter case there may be many classes. Assuming again that class1 and class2 etc never mix, is there some native call that would do this? FYI the string inside $( ) might eventually be a variable. Thanks
Upvotes: 1
Views: 741
Reputation: 6334
it appears that there is no specific answer to this, so here is the thing that I'll write that will address my need:
var menuGroup={
'.group1':{ /*relevant data*/ },
'.group2':{ /*relevant data*/ }
}
var triggers='';
for(var i in menuGroup)triggers+='.'+i+', ';
triggers=triggers.replace(/, $/,'');
$(triggers).click(function(e){
var classes=this.className.split(/\s+/);
for(var i in classes){
for(var j in menuGroup){
if(classes[i]==menuGroup[j].replace(/\./,'')){
var triggerClass=classes[i];
break(2);
}
}
}
//we now have triggerClass..
});
Upvotes: 0
Reputation: 38
$('.class1, .class2, .class3').click(function(e){
alert("Was pressed: "+$(this).attr('class'));
});
Use $(this) to get the invoked element, you can use different methods like hasClass(), addClass(), attr(), etc.
Upvotes: 1
Reputation: 3833
var className = $(e.target).attr('class');
The variable className
should have the class name.
Upvotes: 0