views:

41

answers:

3

I have two variables defined like this:

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

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

$('#a, #b').click(function(e){...});
+3  A: 
$([$a.get(0), $b.get(0)]).click(function(e) { ... });
Darin Dimitrov
Wouldn't it be better to just use $('#a, #b').click() along with $a, $b then?
Vincent
Absolutely, much better, but I thought you don't want to do that and ask how to do it assuming you already have the $a and $b variables.
Darin Dimitrov
Keep in mind this only works on $a and $b's first element. If you change $a or $b to a selector that returns more then one element only the first will be bound. But I agree with Darin $('#a, #b') is a better solution if you only use them once.
fredrik
A: 

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

You could just 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.

..fredrik

fredrik
No, they're not equivalent. The second will make `$b` the context.
Matthew Flaschen
Actually the `$a`.
fredrik
No, the second parameter ($b) is the context.
Matthew Flaschen
I did a test case: var a = $('div'), b = $('span'); $(a,b).click(function { console.log(this) }); console only returns div's.
fredrik
@fred, your example isn't complete. But read [the docs](http://api.jquery.com/jQuery/#jQuery1) on the main function, and it's clear which parameter is which.
Matthew Flaschen
+1  A: 
$a.add($b).click(function(e){...});

add returns a new node set holding the union. $b can be "pretty much anything that $() accepts."

Matthew Flaschen