jQuery/Javascript:在函数中定义全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10389969/
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-24 01:07:36  来源:igfitidea点击:

jQuery/Javascript: Defining a global variable within a function?

javascriptjqueryvariablesglobal

提问by SnarkyDTheman

I have this code:

我有这个代码:

        var one;
        $("#ma1").click(function() {
            var one = 1;
        })
        $("body").click(function() {
            $('#status').html("This is 'one': "+one);
        })

and when I click the body, it says: This is 'one': undefined. How can I define a global variable to be used in another function?

当我单击正文时,它说:这是“一个”:未定义。如何定义要在另一个函数中使用的全局变量?

回答by Rocket Hazmat

Remove the varfrom inside the function.

var从函数内部删除。

    $("#ma1").click(function() {
        one = 1;
    })

回答by keune

If you want to make a global variable bind it to windowobject

如果要将全局变量绑定到window对象

window.one = 1;

回答by Selvakumar Arumugam

    var one;//define outside closure

    $("#ma1").click(function() {
        one = 1; //removed var 
    })
    $("body").click(function(e) {
        $('#status').html("This is 'one': "+one);
    })