It's hard to tell when you don't include complete code, but it's likely that you're running into a closure problem.
You have your onload function defined inside the for loop, which means it'll bind a reference to the "key" local variable. By the time the "unload" function actually runs, the for loop will have been completed, and "key" will be "two", so you'll see "two" in both alerts.
Here's a more-trivial example of the same problem:
for (x=0; x< 2; x++) {
setTimeout(function() {
alert(x);
}, 100);
}
when you run this, you'll get two alerts, each of which shows "2", which is the value of "x" after the loop exits.
To fix this, you need to invoke a function which returns the function you want to call when the timeout happens:
function create_alerter(z) {
return function() {
alert("fixed: " + z);
}
}
for (x = 0; x < 2; x++) {
setTimeout(create_alerter(x), 100);
}
If you don't like having a separate function for this, you can define the function-returning function and invoke it inline:
for (x = 0; x < 2; x++) {
setTimeout(function(z) {
return function() {
alert(z);
}
}(x), 100);
}