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.