I have an click event that I want to assign to more than class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places.
What I want is something like $('.tag' '.tag2'), which of course don't work.
$('.tag').click(function (){
if ($(this).hasClass('clickedTag')){
// code here
}
else {
// and here
}
});
You can select multiple classes at once with jQuery like this:
$('.tag, .tag2').click(function() {
var $this = $(this);
if ($this.hasClass('tag')) {
// do stuff
} else {
// do other stuff
}
});
Giving a 2nd parameter to the $() function, scopes the selector so $('.tag', '.tag2')
looks for tag
within elements with the class tag2
.
$('.tag1, .tag2').on('click', function() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
});
or
function dothing() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
}
$('.tag1, .tag2').on('click', dothing);
or
$('[class^=tag]').on('click', dothing);
$('[class*="tag"]').live('click', function() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
});
It's like this:
$('.tag.clickedTag').click(function (){
// this will catch with two classes
}
$('.tag.clickedTag.otherclass').click(function (){
// this will catch with three classes
}
$('.tag:not(.clickedTag)').click(function (){
// this will catch tag without clickedTag
}
Have you tried this:
function doSomething() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
}
$('.tag1, .tag2').click(doSomething);
Source: Stackoverflow.com