When you add your events, they contain references to the variables you use. In fact, all your events contain references to the exact same variable. During the loop when you add your events, the value of those variables changes. But once the event fires (for any of your elements), they all contain the exact samt value, since they are references to the same variable. And that value is the value they had after the last run through the loop.
Consider
<script type="text/javascript">
// You seem to allready have your cross browser function to add events
function evalAtRunTimeEvent(target, type, f) {
// Non-standard. IE-family
if (target.attachEvent) {
// takes "onclick" etc instead of "click"
type = 'on'+type
target.attachEvent(type, f, false);
}
else {
target.addEventListener(type, f, false);
}
}
/* This function just makes the variable from the loop be turned into
* the function scope variable "localvar", which means that once this function exits,
* "localvar" will only exist for the purpose of the event handler it's used with.
*/
function evalNowDivEvent(target, type, localvar) {
// now we can use the standard function to add event listeners
evalAtRunTimeEvent(target, type, function(e) {
e.target.appendChild(document.createTextNode(localvar))});
}
function addDivEvents() {
var d = document;
// Red border divs - matches the functionality of your script
var divs = d.getElementsByClassName('evalAtRunTime');
for (var i = 0; i < divs.length; ++i) {
evalAtRunTimeEvent(divs[i], 'mouseover', function(e) {
e.target.appendChild(d.createTextNode(i));
});
}
// blue border divs - matches what you're after
var divs = d.getElementsByClassName('evalByLocalizingVar');
for (var i = 0; i < divs.length; ++i) {
evalNowDivEvent(divs[i], 'mouseover', i);
}
}
</script>
<style type="text/css">
div {
border: 1pt solid;
width: 200px;
height: 50px;
margin: 2px;
}
.evalAtRunTime { border-color: red; }
.evalByLocalizingVar { border-color: blue; }
.keepAllVarsInArray { border-color: black; }
</style>
</head>
<body onload="addDivEvents();">
<div class="evalAtRunTime"></div>
<div class="evalAtRunTime"></div>
<div class="evalByLocalizingVar"></div>
<div class="evalByLocalizingVar"></div>