jQuery/[removed] Defining a global variable within

2019-03-26 20:35发布

问题:

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?

回答1:

Remove the var from inside the function.

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


回答2:

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

window.one = 1;


回答3:

    var one;//define outside closure

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