I have the following code that adds an onmouseover event to a bullet onload
for (var i = 0; i <= 3; i++) {
document.getElementById('menu').getElementsByTagName('li')[i].onmouseover = function () { addBarOnHover(i); };
}
This is the function that it is calling. It is supposed to add a css class to the menu item as the mouse goes over it.
function addBarOnHover(node) {
document.getElementById('menu').getElementsByTagName('li')[node].className = "current_page_item"; }
When the function is called, I keep getting the error:
“document.getElementById(“menu”).getElementsByTagName(“li”)[node] is
undefined”
The thing that is stumping me is I added an alert(node) statement to the addBarOnHover function to see what the value of the parameter was. The alert said the value of the parameter being passed was 4. I’m not sure how this could happen with the loop I have set up.
Any help would be much appreciated.
This is a common problem when you close over an iteration variable. Wrap the
forbody in an extra method to capture the value of the iteration variable:an anonymous function is created each time the loop is entered, and it is passed the current value of the iteration variable.
iinside the anonymous function refers to the argument of this function, rather than theiin the outer scope.You could also rename the inner variable for clarity:
Without capturing the iteration variable, the value of
iwhen it is finally used in the anonymous handler has been already changed to4. There’s only oneiin the outer scope, shared between all instances of the handler. If you capture the value by an anonymous function, then the argument to that function is used instead.