I have this code:
i = 60;
i = $(this).find('li a').each(function(i) {
w = $(this).text();
$('#js').text(w);
w = $('#js').width();
if(w > i) {
i = w;
}
return i;
});
It’s wrong :-).
I have X strings ($(this).find('li a')). I want to get the length (px) of the longest one and save its length to variable i that I will use later in my code.
Don’t declare an
iargument on the function you’re givingeach, don’t return anything from theeachfunction, and don’t assign the result ofeachtoi. Then it should work.That way, the function you’re passing into
eachis a closure overiand so can access and update it directly. By declaringias an argument of theeachcallback, you were dealing with a differention each iteration (the one that jQuery passes in, which is the index of the element in the set). And separately, the return value ofeachis the jQuery object on which you call it (docs), which clearly isn’t what you want.More about closures, if you’re not clear on them: Closures are not complicated
In the code above, I also declared the
wvariable as local to theeachcallback, because I’m assuming you don’t have awvariable outside of it you want updated and so were falling prey to The Horror of Implicit Globals.