简体   繁体   English

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

[英]jQuery/Javascript: Defining a global variable within a function?

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? 如何定义要在另一个函数中使用的全局变量?

Remove the var from inside the function. 从函数内部删除var

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

如果要创建全局变量,请将其绑定到window对象

window.one = 1;
    var one;//define outside closure

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM