JQuery - One handler for multiple elements using variables
I have two variables d开发者_Python百科efined like this:
var $a = $('#a'),
$b = $('#b');
How can I rewrite the following line using $a and $b?
$('#a, #b').click(function(e){...});
$([$a.get(0), $b.get(0)]).click(function(e) { ... });
$a.add($b).click(function(e){...});
add
returns a new node set holding the union. $b can be "pretty much anything that $() accepts."
It seems you ca do just this:
$(deleteBtn).add(copyBtn).add(moveBtn).click(function(){});
As it says here http://api.jquery.com/add/
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
精彩评论