2009-07-08 23 views
1
/************************************************************************** 
* 
* Function: toggleVis 
* 
* Description: Following Function hides and expands the main column. 
*    
* 
***************************************************************************/ 
// Set the default "show" mode to that specified by W3C DOM 
// compliant browsers 

    var showMode = 'table-cell'; 


// However, IE5 at least does not render table cells correctly 
// using the style 'table-cell', but does when the style 'block' 
// is used, so handle this 

    if (document.all) showMode='block'; 

// This is the function that actually does the manipulation 

var States = { }; 

function toggleVis(col){ 

    if (!States[col] || States[col].IsOpen == null) 
    { 
     States[col] = {isOpen : true}; // This assumes the cell is already shown 
     //States[col] = {isOpen : false}; // This assumes the cell is already hidden 
    } 

    //mode = States[col].IsOpen ? showMode : 'none'; 
    mode = States[col].IsOpen ? 'none' : showMode; //starts from closed, next click need open 

    cells = document.getElementsByName(col); 
    for(j = 0; j < cells.length; j++) cells[j].style.display = mode; 

    States[col].IsOpen = !States[col].IsOpen; 
} 

該函數隱藏和顯示html表的列。 當我調用此函數時,對象狀態會相應切換,如果展開則爲true;如果爲隱藏或無,則爲false。函數執行一次後,什麼保存狀態的最後一個狀態,以便在再次調用時可以在此函數中使用它?是否因爲對象States {}被聲明爲全局?全局Javascript對象如何保存狀態?

回答

2

是的。您在最外面的閉包中定義了States,這意味着它實際上也是window對象的屬性,即window.States === States。不過,被你定義一個函數像

function foo(param) { 
    var States = param; 
} 

它不會影響全球各國變量,因爲你正在重新定義它爲本地該功能。 (但是,您也可以通過在該函數中使用window.States來訪問全局狀態變量。)

+0

因此,如果它在函數中被操縱但不影響球體,當狀態在函數「States [col] .IsOpen =!States [col] .IsOpen;」 它是如何知道下一次調用函數頂部的是什麼? – 2009-07-08 21:55:59

+0

就你而言,它會影響全局,因爲你不在函數內部重新定義狀態。 – AKX 2009-07-09 14:59:44

1

絕對正確。 States是在全局命名空間中聲明的,並且可用於所有的javascript函數(不會用相同名稱的變量隱藏它)。它會在任何使用它的函數之外保留它的價值。

1

javascript中的全局變量處於活動狀態,直到頁面刷新或卸載。

0

是的,它們是(活動直到刷新); 這是我的問題;我將所有彈出窗口(即未保存的輸入窗體)保存在全局數組中,但刷新後,我無法檢索彈出窗口,因爲我的popup數組的內容爲空;瀏覽器中是否存在一個區域,我可以將數據結構存儲在瀏覽器範圍內?