4

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){...});

4 Answers 4

6
$([$a.get(0), $b.get(0)]).click(function(e) { ... });
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't it be better to just use $('#a, #b').click() along with $a, $b then?
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.
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.
3
$a.add($b).click(function(e){...});

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

Comments

0

It seems you ca do just this:

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

As it says here http://api.jquery.com/add/

Comments

-1

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

4 Comments

No, they're not equivalent. The second will make $b the context.
No, the second parameter ($b) is the context.
I did a test case: var a = $('div'), b = $('span'); $(a,b).click(function { console.log(this) }); console only returns div's.
your example isn't complete. But read the docs on the main function, and it's clear which parameter is which.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.