Is there any difference between jquery code?

Here is the code block a

$('ul.filter li').each(function() { $(this).click(function(e) { //do something }); }); 

Here is code block b

 $('ul.filter li').click(function(e) { //do something }); 

Don't they do the same? better than the other? Which one is better / faster? I would suggest block b, since it has less code, but I want to confirm it here, thanks

+4
source share
5 answers

The effect you see will be the same, but in the first case, a new function is assigned to each li element, since you create a function object inside the each callback.

In the second case, there is only one copy of the event handler, which means that it uses less memory for everyone (although this is probably not measurable).

Internally, click calls on (in jQuery 1.7), which iterates over the elements through each , as well :

 return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); 

This applies to many jQuery methods (most often noted in the documentation), so you save characters and memory by letting jQuery implicitly do this.

+7
source

They would both have the same effect.

I would prefer the second option only because it is shorter and you create one anonymous function to handle the click, rather than an anonymous function for each element.

+2
source

For jQuery philosophy, the second is better because it is shorter.

+1
source

Both are more or less the same and give the same results. The second code snippet will also execute each inner loop and assign a click handler to each li element.

But yes, the second code fragment is very clear and simple.

+1
source

The second use is called "implicit iteration" and is one of the cornerstones of jQuery.

For example, in the JavaScript Definition Guide, 6th ed., P. 530 for jQuery basics:

Despite the strength of each method (), it is not very often used, since jQuery methods are usually implicitly repeated over the set of matched elements and operate on them all. Usually you only need to use each () if you need to manipulate the matched elements in different ways. Even then, you may not need to call each (), since the number of jQuery methods allows you to pass a callback function.

at http://jqfundamentals.com/chapter/jquery-basics

Implicit iteration means that jQuery automatically iterates over all the elements in the selection when you call the setter method on that selection. This means that when you want to do something for all the elements in the selection, you do not need to call the setter method on each element in your choice - you just call the method of the choice itself, and jQuery iterates over the elements for you.

As a rule, when the library has this built-in standard way to do this, it will be generally better and faster, otherwise they would not have built it.

0
source

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


All Articles