JQuery Combined / Chain Multiple Object

var $obj1 = $('a#one'); var $obj2 = $('a#two'); var $obj3 = $('a#three'); // Assume $('a#one, a#two, a#three') wasn't an option. 

How to assign one (the same) event handler, for example. click() for these three jQuery objects? Essentially, I'm looking for a more efficient way:

 $obj1.click(function() { /* Code A */ }); $obj2.click(function() { /* Code A */ }); $obj3.click(function() { /* Code A */ }); 
+6
source share
4 answers

Only (very) a little shorter, but:

 $([$obj1, $obj2, $obj3]).click(function() { }); 

You would like to define your handler outside of the first anonymous function, so you really would be better off using the Jonas H. method by simply adding another sentence.

Note: you can technically make a hybrid, but it's quite long:

 var f = function() { }; $([$obj1, $obj2, $obj3]).click(f); 

Indeed, this question is only useful if you want to avoid $ a.click (f) again and again, which is really a better option than this abuse of jQuery. :)

+7
source

Hmm, always .add() , but personally, I prefer to write .click() functions one by one if I started with separate variables anyway. There is no need to purchase additional overhead by creating new jQuery objects for such trivial functions.

 $obj1.add($obj2).add($obj3).on('click' , function () { } ); // not sure if $obj1.add($obj2, $obj3) will work as well 
+2
source
 var myFunction = function() { /* Code A */ }; $obj1.click(myFunction); $obj2.click(myFunction); $obj3.click(myFunction); 
+1
source

get the generic parent container and use jQuery .on() on it.

 <div id="parent"> <a href="#" id="one">1</a> <a href="#" id="two">2</a> <a href="#" id="three">3</a> </div> //any <a> clicked under parent executes this function $('#parent').on('click','a#one, a#two, a#three',function(){ //do stuff }); 

its best part: it is only one handler, and in the parent. you do not put multiple handlers on multiple elements. plus, when you modify a handler, it takes effect for everyone. there is no need to individually change the handlers for each element that has one. demo here


http://api.jquery.com/on/

In addition to their ability to handle events on children that are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements need to be controlled. In a data table with 1000 rows in the body, this example attaches a handler to 1000 elements:

The approach with delegated events binds the event handler to only one element , that is, and the event should only bubble at the same level (from clicking tr to tbody).

0
source

Source: https://habr.com/ru/post/910881/


All Articles