Recently i got stuck on an issue when using DOM event handlers. Next i´ll describe the problem related stuff:
The code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form >
<input id="b1" type="submit" value="Click" />
</form>
<script>
//global variable
var v= 0;
var b1= document.getElementById("b1");
b1.addEventListener("click", f1, false);
function f1() {
window.alert(++v);
}
</script>
</body>
</html>
How the code should work?
When the button(b1) is pressed, the global variable(v) increases its value progressively for each new click of the button.The window will alert the new value.
The problem:
The variable doesnt keep its latest value.For example, when i click the button twice, the window should alert 2 but instead im still getting 1.
Assertions:
- The global variable(v) should keep the changes done to it inside a function.This is due the fact that im using it directly on the function,without using an argument.
Notes:
When i invoke the function twice directly on the code it works correctly(instead of the handler).
f1();//1
f1();//2
I´ve tested it with Chrome and Firefox.
So, what´s happening here? why doesn´t it works correctly? does the event handler works differently with the global variables?
Hope you guys can help me! Thanks!