jQuery 更改函数内的全局变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19218031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:27:11  来源:igfitidea点击:

Changing global variable value inside function

javascriptjquery

提问by sakir

Here is my simple scenario. I have a variable defined inside the ready()function which assigns the first value.

这是我的简单场景。我在ready()函数内部定义了一个变量,它分配了第一个值。

I also have a function outside ready(). What I want to do is to use the changed variable inside my new function.

我在外面也有一个功能ready()。我想要做的是在我的新函数中使用更改后的变量。

Here is my JavaScript code:

这是我的 JavaScript 代码:

var myFunction = function() {
    // I wanna change Vp value here and wanna 
    // use this function with the new value        
    Vp = "new value";

    myFunction2 (); 
};

$(document).ready(function () {

    var Vp = "first value asign";
    $('#btnAddCustomer').click(myFunction);

    var myFunction2 = function() {
        // I will use Vp variable here with new value
    };
});

回答by aIKid

Discard the varstatement. It assigned the value to a new local variable, instead of the global variable.

丢弃var声明。它将值分配给一个新的局部变量,而不是全局变量。

Here:

这里:

var Vp = "first assigned value"
var myFunction2;

var myFunction = function() {
    // I wanna change Vp value here and wanna use this function with the new value        

    Vp =  "new value"
    myFunction2(); 

    };

$(document).ready(function () {

    Vp = "first value asign";

    $('#btnAddCustomer').click(myFunction);

    myFunction2 = function() {

    alert(Vp)

    };

});

Fiddle: http://jsfiddle.net/XGGvv/10/

小提琴:http: //jsfiddle.net/XGGvv/10/

NOW THAT WORKS.

现在可以了。

A nice reading on JS variable scopes: http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

关于 JS 变量范围的一个很好的阅读:http: //coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/