Closure Test

by questwork

HTML

<p><b>Question:</b></p>
Why do the anchors, when clicked on, alert "-1" instead of "0" and "1"? How could we fix that?

<p><b>題目:</b></p>
为什麽按下去,兩個連結都是提示"-1",而不是"0"和"1"呢?我們可以怎樣修改呢?

<p><a href="#">zero</a></p>
<p><a href="#">one</a></p>

JavaScript

var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
    as[i].onclick = function() {
        alert(i);
        return false;
    }
}