2011-02-15 14 views
0

爲什麼我無法獲得此功能?在點擊時設置VAR並提醒您的值

我想從菜單中獲取index(),並在hash更改時獲取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

通過使用`var`,你正在使'click'功能的`index`變爲本地。 – 2011-02-15 11:30:28

回答

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); 
}); 

我建議在範圍界定在JavaScript中是如何工作的閱讀了 - JS Garden有一個體面的概述。

0

變量index與調用alert的範圍不在同一範圍內。

你可以宣佈其爲兩種功能前一個全局變量:

var index; 

然後取出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); 
    });