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
The effect you see will be the same, but in the first case, every
lielement is assigned a new function, as you are creating the function object inside theeachcallback.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,
clickcallson(in jQuery 1.7), which is iterating over the elements viaeachas well: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.