문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top