2011-02-15 3 views
0

왜이 기능을 사용할 수 없습니까 ??클릭 할 때 VAR 설정 및 값 경고

메뉴에서 index()를 가져오고 해시가 변경 될 때 값을 alert()하고 싶습니다.

경고가 나타나지 않습니다.

$('#menu li a').click(function() { 
     var index = $(this).parent().index()+1; 
    }); 



    $(window).bind('hashchange', function() { //detect hash change 
     var hash = window.location.hash.slice(1); //hash to string (= "myanchor") 
     alert(index); 
    }); 

내가 뭘 잘못하고 있는지 말해 줄 수 있습니까 ??? ???

+2

을 'index'를'click' 함수에 국한시키고 있습니다. –

답변

2

이것은 범위 지정 문제이며 index 변수는 선언 된 함수에 대해 로컬이므로 다른 함수에서 액세스 할 수 없습니다. 외부 범위에 선언을 이동하고 그것은 작동합니다 : 나는 범위 지정 자바 스크립트에서 작동하는 방법에 독서를 권장합니다

var index; // declare the variable 
$('#menu li a').click(function() { 
    // Assign the value, notice the `var` keyword isn't there anymore 
    index = $(this).parent().index() + 1; 
}); 

$(window).bind('hashchange', function() { //detect hash change 
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor") 
    // Get the value 
    alert(index); 
}); 

을 - JS Garden 괜찮은 개요있다.

0

변수 indexalert 호출과 동일한 범위에 속하지 않습니다.

당신은 두 기능 전에 전역 변수로 선언 할 수있다 :

var index; 

그리고 첫 번째 함수에 var 키워드를 제거하십시오,`var`를 사용하여

$('#menu li a').click(function() { 
    index = $(this).parent().index()+1; 
}); 
0
var index; 
    $('#menu li a').click(function() { 
     index = $(this).parent().index()+1; 
    }); 



    $(window).bind('hashchange', function() { //detect hash change 
     var hash = window.location.hash.slice(1); //hash to string (= "myanchor") 
     alert(index); 
    }); 
관련 문제