9

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 Answers 3

21

Remove the var from inside the function.

    $("#ma1").click(function() {
        one = 1;
    })
Sign up to request clarification or add additional context in comments.

2 Comments

To expand upon why this works, when you used var inside the function, you created a new and separate local variable. By removing the var, you are essentially saying you want to look up the chain for a previously defined variable (in this case the global one).
Thanks for your help, Rocket. That saved me.
14

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

window.one = 1;

Comments

12
    var one;//define outside closure

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.