Darkry
Darkry

Reputation: 590

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.

Upvotes: 5

Views: 10353

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

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.

Upvotes: 14

Related Questions