Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ,each() - return value

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.

like image 893
Darkry Avatar asked Dec 12 '22 11:12

Darkry


1 Answers

Don't declare an i argument on the function you're giving each, don't return anything from the each function, and don't assign the result of each to i. Then it should work.

i = 60;
$(this).find('li a').each(function() {
    var w = $(this).text();
    $('#js').text(w);
    w = $('#js').width();
    if(w > i) {
        i = w;
    }
});

That way, the function you're passing into each is a closure over i and so can access and update it directly. By declaring i as an argument of the each callback, you were dealing with a different i on each iteration (the one that jQuery passes in, which is the index of the element in the set). And separately, the return value of each is 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 w variable as local to the each callback, because I'm assuming you don't have a w variable outside of it you want updated and so were falling prey to The Horror of Implicit Globals.

like image 90
T.J. Crowder Avatar answered Dec 25 '22 18:12

T.J. Crowder