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);
})
Author by
SnarkyDTheman
Coder Of Codes. Purveyor of cheese. Holy Mexican monkey butt homo hot lips.
Updated on August 02, 2022Comments
-
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 about 12 yearsTo expand upon why this works, when you used
var
inside the function, you created a new and separate local variable. By removing thevar
, you are essentially saying you want to look up the chain for a previously defined variable (in this case the globalone
). -
SnarkyDTheman about 12 yearsThanks for your help, Rocket. That saved me.