JQuery - one handler for multiple elements using variables

I have two variables defined as follows:

var $a = $('#a'), $b = $('#b'); 

How can I rewrite the next line using $ a and $ b?

 $('#a, #b').click(function(e){...}); 
+4
source share
4 answers
 $([$a.get(0), $b.get(0)]).click(function(e) { ... }); 
+6
source
 $a.add($b).click(function(e){...}); 

add returns a new node set containing the union. $ b could be "almost anything that accepts $ ()".

+3
source

It seems you are just doing this:

 $(deleteBtn).add(copyBtn).add(moveBtn).click(function(){}); 

As the saying goes here http://api.jquery.com/add/

0
source

Depends on what you want to do next with your vars.

You can simply define them as one:

 var $a = $('#a, #b'); $a.click() 

Or use them separately:

 /* This way the click event is applied even if each selector returns more then one element. And $a and $b is preserved */ $([].concat($a.toArray()).concat($b.toArray())).click(function () { console.log(this) }); 

EDIT

Updated code.

.. Fredrick

-1
source

All Articles