Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a difference between the jquery code here?

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 these do the same thing? is one better than the other? Which one is the better/faster method? I would assume block b since it has less code but I want to confirm it here, thanks

like image 262
Huangism Avatar asked Dec 21 '22 03:12

Huangism


2 Answers

The effect you see will be the same, but in the first case, every li element is assigned a new function, as you are creating the function object inside the each callback.

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

Internally, click calls on (in jQuery 1.7), which is iterating over the elements via each as well:

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

This is the case with many jQuery methods (most often noted in the documentation), so you are saving characters and memory by letting jQuery implicitly do this.

like image 124
Felix Kling Avatar answered Jan 04 '23 01:01

Felix Kling


They would both have the same effect.

I would prefer the second only because it is more concise and you're creating a single anonymous function to handle the click rather than an anonymous function per element.

like image 45
Justin Niessner Avatar answered Jan 04 '23 02:01

Justin Niessner