/**************************************************************************
*
* 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 {}被声明为全局对象?
最佳答案
是。您在最外层的闭包中定义States
,这意味着它实际上也是window
对象的属性,即window.States
=== States
。但是,您是否定义了一个像
function foo(param) {
var States = param;
}
它不会影响全局States变量,因为您将其重新定义为该函数的局部变量。 (但是,您也可以通过在该函数中使用
window.States
来访问全局States变量。)关于javascript - 全局Javascript对象如何保存状态?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1100431/