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

37,071

Solution 1

Remove the var from inside the function.

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

Solution 2

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

window.one = 1;

Solution 3

    var one;//define outside closure

    $("#ma1").click(function() {
        one = 1; //removed var 
    })
    $("body").click(function(e) {
        $('#status').html("This is 'one': "+one);
    })
Share:
37,071
SnarkyDTheman
Author by

SnarkyDTheman

Coder Of Codes. Purveyor of cheese. Holy Mexican monkey butt homo hot lips.

Updated on August 02, 2022

Comments

  • SnarkyDTheman
    SnarkyDTheman almost 2 years

    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?

  • Moses
    Moses about 12 years
    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).
  • SnarkyDTheman
    SnarkyDTheman about 12 years
    Thanks for your help, Rocket. That saved me.