gpt4 book ai didi

javascript - 全局 Javascript 对象如何保存状态?

转载 作者:行者123 更新时间:2023-11-30 10:56:23 25 4
gpt4 key购买 nike

/**************************************************************************
*
* 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 表格的列。当我调用此函数时,对象状态会相应地切换,如果展开则为真,如果隐藏则为假或无。函数执行一次后,用什么保存States的最后一个状态,以便再次调用时可以在这个函数中使用?是因为对象 States{} 被声明为全局的吗?

最佳答案

是的。您在最外层的闭包中定义了 States,这意味着它实际上也是 window 对象的一个​​属性,即 window.States == = 状态。但是,您是否要定义一个像

这样的函数?
function foo(param) {
var States = param;
}

它不会影响全局 States 变量,因为您将它重新定义为该函数的局部变量。 (但是您也可以通过在该函数中使用 window.States 来访问全局 States 变量。)

关于javascript - 全局 Javascript 对象如何保存状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1100431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com