var $obj1 = $('a#one');
var $obj2 = $('a#two');
var $obj3 = $('a#three');
// Assume $('a#one, a#two, a#three') wasn't an option.
How do I assign one (same) event handler e.g. click()
to those three jQuery objects? Essentially, I am looking for a more efficient way of doing:
$obj1.click(function() { /* Code A */ });
$obj2.click(function() { /* Code A */ });
$obj3.click(function() { /* Code A */ });
Only (very) marginally shorter, but:
$([$obj1, $obj2, $obj3]).click(function() { });
You would want to define your handler outside of the first anonymous function though, so you'd really probably be better off with Jonas H's method. Just throwing another suggestion out there.
Note: you could technically do a hybrid, but it's quite lengthy:
var f = function() { };
$([$obj1, $obj2, $obj3]).click(f);
Really this question is only useful if you want to avoid the $a.click(f) over and over again, which is truly a better option than this jQuery abuse. :)
Hmm, there's always .add()
, but personally I prefer writing out the .click()
functions one by one, if I started out with seperate variables anyway. No need to acquire additional overhead creating new jQuery objects for such trivial functionality.
$obj1.add($obj2).add($obj3).on('click' , function () { } );
// not sure if $obj1.add($obj2, $obj3) will work as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With