josh
josh

Reputation: 3

jquery - how could I bind the same things to 2 diffrent classes?

I have got:

$('.class1').click(function(){   //do
things on $(this) element })

and

$('.class2').click(function(){
  //do things on $(this) element
})

things to do in each of that is the same, but when I did:

$('.class2').click(function(){
   $('.class1').click();
})

... it was disaster, that actived each element with class1. Is there any similar solution to above one?

Upvotes: 0

Views: 76

Answers (3)

Felix Kling
Felix Kling

Reputation: 816830

Using the multiple selector is the best way here. However in some situations, you have to bind the handlers dynamically. Use named functions then:

function handler() {
    // something
}

$('.class1').click(handler);
$('.class2').click(handler);

Upvotes: 1

Chandu
Chandu

Reputation: 82933

Try this:

$('.class1, .class2').click(function(){   
  //do things on $(this) element 
}) ;

Upvotes: 2

Alex
Alex

Reputation: 7374

$(".class1,.class2").click(function(){ });

Upvotes: 1

Related Questions