Having a problem 开发者_StackOverflowunderstanding what I will call a variable scope question for lack of a better description.
Say I have a page with two functions, one()
and two()
. The first function has a locally-scoped variable x
with an object in it. This function builds an element, below, in the DOM and this element contains an onClick
, which calls the second function, and needs to pass x
to the second function as an argument. I.e. the second function needs access to the data that is scoped to the first function.
I have tried:
<something onClick="two(x);">
but this doesn't seem to work. I know that there is a way to make x
global but I have found in my other languages that globally-scoped variables are discouraged as being dangerous.
How about using closure:
function one()
{
var x = Math.random();
var el = document.createElement('div');
el.innerHTML='Hi!';
el.addEventListener("click", function(){two(x)}, false);
document.getElementById('myDiv').appendChild(el);
}
function two(text)
{
alert(text);
}
one();
Demo
Using a global variable within a function is not necessarily bad, but it is considered bad practice to place variables in the window scope, which is assumed if you don’t wrap your variables inside a function or object.
Consider this example:
(function() {
var x = 1;
function callback() {
alert(x);
}
function bind() {
x++;
elem.onclick = callback;
}
}());
You should read up on variable scope.
The function closure of one()
has access to x. But since it exists in one()
and not outside other functions will not have access to it. So you are putting two(x);
in your onClick, which will try to resolve the x
to a global scope. And there is no global x
You can easily fix this by making x
global. Just place var x
beside your functions.
to make x global declare it outside of the method
var x = 0
function one()
x=1
function two()
print x
x will print 1
精彩评论