I am trying to use anonymous function for adding handler to anchor objects.
I run this code but it doesn’t work can you explain why and try to fix it? Thanks:
var obj = document.getElementsByTagName("a");
var items = ["mouseover", "mouseout"];
for (var i = 0; i < items.length; i++) {
(function() {
var item = items[i];
for (var i = 0; i < obj.length; i++) {
obj[i]["on" + item] = function() {
alert("thanks for your " + item);
};
}
})();
}
iis “hoisted”; in other words, your function is being executed as:So
iinitems[i]is not referring to the outeri. Instead,iisundefined. You should use separate variable names, e.g.jfor the inner loop:Second,
itemwill change so the alert will use the same value each time. To circumvent this, you can use an anonymous function, but the point in them is to pass the value so that it “freezes”: