JavaScript for loop index strangeness

Posted by pythonBOI on Stack Overflow See other posts from Stack Overflow or by pythonBOI
Published on 2010-05-10T14:23:53Z Indexed on 2010/05/10 14:34 UTC
Read the original article Hit count: 184

Filed under:
|
|

I'm relatively new to JS so this may be a common problem, but I noticed something strange when dealing with for loops and the onclick function. I was able to replicate the problem with this code:

<html>
<head>

<script type="text/javascript">
window.onload = function () {
    var buttons = document.getElementsByTagName('a');
    for (var i=0; i<2; i++) {
        buttons[i].onclick = function () {
            alert(i);
            return false;
        }
    }
}

</script>

</head>

<body>
<a href="">hi</a>
<br />
<a href="">bye</a>

</body>

</html>

When clicking the links I would expect to get '0' and '1', but instead I get '2' for both of them. Why is this?

BTW, I managed to solve my particular problem by using the 'this' keyword, but I'm still curious as to what is behind this behavior.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about onclick