Could someone please explain, why do we need each(function (i)
what does (i) do? seems like i could be any letters.
why (i) is necessary? I don’t quite understand. Many Thanks
<body>
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>
<script>
$(document.body).click(function () {
$( "div" ).each(function (i) {
if ( this.style.color != "blue" ) {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
</script>
The first parameter for the callback function is the index of the iteration in the loop. i.e. the loop counter. In your case you don’t need it at all, as you are not using it:
The second parameter is the element for the current iteration, i.e. the same as
thisis referring to. You could use that parameter instead ofthis. Of course, to use the second parameter you have to specify the first parameter also, even if you don’t use it: