Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - One handler for multiple elements using variables

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){...});
like image 463
Vincent Avatar asked Feb 26 '23 01:02

Vincent


2 Answers

$([$a.get(0), $b.get(0)]).click(function(e) { ... });
like image 130
Darin Dimitrov Avatar answered Mar 03 '23 15:03

Darin Dimitrov


$a.add($b).click(function(e){...});

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

like image 36
Matthew Flaschen Avatar answered Mar 03 '23 14:03

Matthew Flaschen