2012-08-14 120 views
3

我以前問過這個問題,但從來沒有真正得到它的工作。全局變量jquery

或多或少,我有多個JS文件,我需要檢查對一個變量。我有一個函數,檢查是否存在一個類,然後更改該變量。

var states = function(){ 

    if($('#Animation.switch.switchOff').length == 1){ 
     animationtoggle = 0; 
    } 
    else { 
     animationToggle = 1 ; 
    } 
    if($('#Autoscroll.switch.switchOff').length == 1){ 
     scrolltoggle = 1; 
    } 
    else { 
     scrolltoggle = 0  
    } 
    return { 
     animationtoggle: animationtoggle, 
     scrolltoggle: scrolltoggle 
    }; 
} 

然後我有另一個函數內,在另一個JS文件這樣的:

Okay, I've done this, although It still doesn't fix my problem of being able to use this variable on another file, I have this inside the function: 

$(function() { 
    var ss = states(); 
    ss.animationtoggle; 
    var last_position = 0; 
    var duration = 300; 
    if (animationtoggle == 1){ 
     //only do something if it's equal to 1 "on" 
}); 

這是切換按鈕代碼:

$('#optionMenu ul li').click(  
function() { 
$(this).toggleClass('switchOff'); 
var ss = states(); 
ss.scrolltoggle; 
ss.animationtoggle; 
}); 

上午我處理這個正確的方式?

請幫忙!這裏是我的地盤,切換到了右上角的那一刻:http://shannonhochkins.v5.cloudsvr.com.au/

+3

這是要成爲全球訪問的問題的變量?酷站點btw。 – Jeemusu 2012-08-14 02:12:02

+0

都scrolltoggle和animationtoggle @Jeemusu – Shannon 2012-08-14 02:16:02

+0

所以你有什麼問題,你的變量不改變正確,其實你已經宣佈VAR animationtoggle = 1,如果你希望它是全球性的聲明它 - > animationtoggle = 1, – 2012-08-14 02:25:51

回答

1

我相信你是通過創建和分配相同的變量多次覆蓋它們。全局變量應該定義在特定函數的範圍之外,最好接近頁面加載的第一個操作。全局變量被分配給窗口對象,並且可以在聲明後按名稱訪問。

//You need to define your global variable out of the scope of your function 
var ss = states(); 

$(function() { 
if (ss.animationtoggle == 1){ 
    //only do something if it's equal to 1 "on" 
}); 

$('#optionMenu ul li').click(  
function() { 
$(this).toggleClass('switchOff'); 
//Don't create the same variable here with the same name 
//Instead access the global variables by using them 
// ss.scrolltoggle; 
// ss.animationtoggle; 
}); 
+0

仍然沒有運氣,我已經得到了它的工作在同一個JS文件,但對他人的變量的變化不工作,我使用的是相同的queeries,但它不是加工! – Shannon 2012-08-14 02:38:58

+0

剛剛更新我的答案,試圖更清楚一點。 – Matt 2012-08-14 02:54:17

0

嘗試改變

var animationtoggle = 1, 

animationtoggle = 1, 

,並將其移出功能。如果不是他們將重新初始化,並且再次

0

嘗試在功能重命名變量,以避免混淆:

var animationtoggle = 1; 
... 

var _animationtoggle = 1; 
... 
return { animationtoggle : _animationtoggle, ....} 

或代替你的函數如下:

return { 
     animationtoggle: ($('#Animation.switch.switchOff').length == 1)?0:1, 
     scrolltoggle: ($('#Autoscroll.switch.switchOff').length == 1)?1:0 
};