I am trying to move from $.each() to a for() statement but experiencing some issues with the usage of $(this) in the later ?
i.e. assume I have this function
$('.class').each(function() {
var myVar = $(this);
var myVarSrc = myVar.attr('src');
...
The problem I experiencing is that when I attempt to move this to a for statement
var class = $('.class');
for (var i = 0; i < class.length; i++) {
var myClass = $('.class')[i];
var myClassSrc = myClass.attr('src');
...
The later doesn’t bind to each meaning that myClassSrc – if it’s the same – will overwrite ? How can I use a for statement with this ?
Doing
[i]extracts the native DOM element.If you do that, you should access the
.srcproperty directly.…or use the
eq()[docs] method to get a jQuery object with the element for the given index:Also notice that I removed the
$('.class')from inside the loop. You should use the cached version you made before the loop.I also changed the variable name from
classtoclssinceclassis a future reserved word in JavaScript.Based on the comments below, you’ve come a cross a very common issue. Because you’re assigning event handlers inside the
forloop, and because JavaScript does not haveblock scope, this means that every handler you create in the loop is referencing the samemyClassSrcvariable, which will be set at whatever value it was after the loop completed.In order to scope a variable, you need to create the event handler in a new variable scope that references the value in the current iteration. To do this, we simply pass whatever value we want to retain into a function invocation, and create the handler there: