jQuery/[removed] Defining a global variable within

2019-03-26 20:54发布

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?

3条回答
倾城 Initia
2楼-- · 2019-03-26 21:11
    var one;//define outside closure

    $("#ma1").click(function() {
        one = 1; //removed var 
    })
    $("body").click(function(e) {
        $('#status').html("This is 'one': "+one);
    })
查看更多
对你真心纯属浪费
3楼-- · 2019-03-26 21:14

Remove the var from inside the function.

    $("#ma1").click(function() {
        one = 1;
    })
查看更多
贪生不怕死
4楼-- · 2019-03-26 21:15

If you want to make a global variable bind it to window object

window.one = 1;
查看更多
登录 后发表回答