George Wilson
George Wilson

Reputation: 5705

Return a value from a nested each function

I'm trying to get the hash of a url and compare it to a list of href's in a list. Below is the relevant portion of my code

                //ON PAGE LOAD
                var hash = document.URL.substr(document.URL.indexOf('#')+1);
            hash = '#' + hash;
            if(hash)
            {
                $( "#tab ul li a" ).each(function( index ) {
                  if(hash==$(this).attr('href'))
                  {
                    alert(index);
                    return index;
                  }
                });
            }
            alert(index);
            //DO STUFF WITH INDEX

The problem is that the nested function isn't returning the index value (its definitely being set). The first alert is returning a number - the second however is returning undefined.

How do I go about returning the index of the matched value?

Upvotes: 0

Views: 473

Answers (2)

fmsf
fmsf

Reputation: 37147

You cannot return stuff in the middle of your each. At most you can return false to break the loop. Use a placeholder variable to store the value you want and then break the loop.

            var returnValue;
            $( "#tab ul li a" ).each(function( index ) {
              if(hash==$(this).attr('href'))
              {
                alert(index);
                returnValue = index;
                return false; // breaks the each
              }
            });

when you do ...each(function(... you are creating a function that will be called inside the each. So if you return something in it, the return value will be read somewhere inside the each code, which will keep executing and return something else (normaly another jQuery object to allow chainability). The each actually expects you to return something if you want. And that is for example false so that it stops iterating through the list of nodes.

Upvotes: 2

Dave
Dave

Reputation: 46259

You should store it in a variable which is defined before the loop, then return false to stop the loop. (each's return value is only used to determine whether the loop should stop early)

Example:

var returned;
$( "#tab ul li a" ).each(function( index ) {
    if(hash==$(this).attr('href')) {
        returned = index;
        return false;
    }
});
// returned contains the value, or undefined

Upvotes: 1

Related Questions