I do not understand the behavior below.
I am expecting the script below to do the following:
- Get all elements with the class 'button'
- For each element with button, assign an onclick event
- When the user clicks a button, there's an alert with the current value of
iwhen the onclick was assigned.
So I would expect clicking "Button 1" would alert "I am button 1".
Instead all 3 buttons alert "I am button 3". It looks like the i counter's value isn't be retained.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<p class="button">Button 0</p>
<p class="button">Button 1</p>
<p class="button">Button 2</p>
<script>
var buttons = document.getElementsByClassName('button');
for (var i=0 ; i < buttons.length ; i++){
buttons[i].onclick = function(){
alert("I am button " + i);
};
}
</script>
</body>
</html>
Why does this happen? How can I achieve the desired behavior?