Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple class events together , how to get the current class name

Tags:

jquery

I have multiple class events bind together for a click event ,

i want to know which class is clicked , how can i get current user selected class

$('.class2 , .class3 , .class3').bind('click', function () {
    location.href = "test.htm";
});
like image 447
kobe Avatar asked Nov 05 '10 18:11

kobe


People also ask

How do you find the class name in an event target?

You can use jQuery to check for classes by name: $(event. target). hasClass('konbo');

How do you call multiple classes in Javascript?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.


3 Answers

You can use .className like this:

$('.class2 , .class3, .class3').bind('click', function() { 
  alert(this.className);
  location.href = "test.htm"; 
});

It can be anywhere from 1 to 3 of those classes though, including other unrelated classes.

Or, since you only actually have 2 if you want to test it using .hasClass() that's an option as well:

$('.class2 , .class3').bind('click', function() { 
  var c = $(this).hasClass("class2") ? "class2" : "class3";
  alert(c);
  location.href = "test.htm"; 
});
like image 169
Nick Craver Avatar answered Nov 15 '22 05:11

Nick Craver


You can use .hasClass()

$('.class1 , .class2 , .class3').bind('click', function() { 
  if($(this).hasClass('class1')) {
    location.href = "test1.htm"; 
  } else if($(this).hasClass('class2')) {
    location.href = "test2.htm"; 
  } else if($(this).hasClass('class3')) {
    location.href = "test3.htm"; 
  }
});
like image 40
generalhenry Avatar answered Nov 15 '22 03:11

generalhenry


You could use the hasClass method ala:

if($(this).hasClass('class2'))

Though I'm not sure how many classes you'd look through or what exactly you need it for so it might not be the best route :)

like image 24
Gazillion Avatar answered Nov 15 '22 03:11

Gazillion