3

I'm trying to change a global variable by setting it as a parameter in a function. The problem I'm running into is that my global variable does not change when I change the local variable. I understand that the scope of the variables is what's causing this, but I do not know how to make it work. Here is the code I'm using:

    var blnUpgradeGlobal;

    function SelectUpgrade(strUpgradeName, blnUpgradeLocal) {
        if (blnUpgradeLocal) {
            blnUpgradeLocal= false;
            $("#" + strUpgradeName).css("background-color", "#EAC300")
        }
        else {
            blnUpgradeLocal= true;
            $("#" + strUpgradeName).css("background-color", "Lime")
        }
    }

<div id="Upgrade1" onclick="SelectUpgrade(this.id, blnUpgradeGlobal)">
Content
</div>  

So What I'm trying to accomplish here is so that when the user clicks the div, it toggles the boolean global variable set in the onClick event. I don't want to specify the exact variable in the function because I would then need to write a big nested if statement because there are a bunch of upgrades.

Thank you in advance.

4

3 回答 3

3

There are 2 possible options:

  1. Change the 2nd parameter name (from blnUpgradeLocal to something else) in the function declaration

  2. Change the global variable value using window.blnUpgradeGlobal reference

The former is better

于 2013-06-18T22:11:50.197 回答
3

可以在代码中的任何位置访问和更改全局变量。
摆脱参数,然后使用它。
发生的事情是您传入全局值但仅更改本地 var 的值,因为首先搜索本地命名空间

于 2013-06-18T22:12:46.983 回答
0

我不想在函数中指定确切的变量,因为我需要编写一个大的嵌套 if 语句,因为有一堆升级

那么你最好的选择是将所有这些全局变量包装在一个对象中(它在全局命名空间中的污染也更少)。像这样的东西:

var globalVars = {
    foo: true,
    bar: 1,
    baz: 'foo'
};

然后,在您的函数中,只需引用该对象(如果它不是全局的,您可以改为传递它):

function doStuff(glb) {
    glb.foo = false;
    glb.bar = 2;
}
doStuff(globalVars);
于 2013-06-18T22:25:28.357 回答