I am really confused about each function.
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
//$(".a").click(function(){
// alert("hi");
//});
$(".a").each(function(){
$(this).click(function(){
alert("hi");
});
});
});
</script>
</head>
<body>
<div class="a">hi</div>
<div class="a">hi</div>
</body>
</html>
What’s the difference between using .click function directly and using .each? Both of them works.
Thanks a lot.
EDIT
If these two methods are the same, could you please give an example why .each is necessary?
Actually there is a difference here. With
.eachyou create a new function in every iteration and each element gets a different function object assigned as event handler.This is not the case if you call
.clickon the whole selection. It will use the function you pass to it as event handler for each element. The behaviour in the end is the same though.You could avoid creating a new function object by creating it once before you iterate over the elements:
But it is unnecessary to do so.
.clickcalls.oninternally which in turn will call.eachto iterate over the selected elements and bind the event handler..eachis just a generic way to iterate over the elements and do whatever you want with them. For example, you might want to replace a word inside each element by another word:This is not a very good example because also here there is a neater way to do it, but I hope it gives you some idea.
Why is there a performance difference between these two ways?
The outer
.eachcall is redundant and adds an additional overhead. The “call chain” will look similar to this:In comparison, this is roughly what happens when you call
.clickdirectly:So not only are more functions executed, but additional, the same functions (like
.clicknad.on) are executed multiple times. Each function might make checks or initialise variables once per call, so obviously if you call it multiple times, it will take more time.