It is simple: I need to register an event property with a function. But in order to pass arguments to the function, I create a closure.
var x=0
function foo(bar1,bar2){
return function (){
alert (bar1+bar2);
x++;
}
}
for (var i=0;i<document.getElementsByTagName("div").length;i++) {
document.getElementsByTagName("div")[i].onclick=foo(x,i)
}
Since I have 5 div elements, and I thought it should alert like this if I click all the div from top to down:
0 2 4 6 8
but instead it output:
0 1 2 3 4
It seems like that every time in foo(x,i), x is equal to 0. How do I get foo() to access the new value of x instead of its first initiation?
xbut not using it in the addition in the function. JavaScript always passes by value, so when you didfoo(x,i);it made a copy of the value0. If you want the handler to use the current state ofx, then don't passxtofoo(). Just passi, and inside the handler doalert(x + bar1);. jsFiddle DEMO