为什么在此代码i
中超出范围?callback function
// All menu items collection
var menuItems = document.getElementsByClassName('menu-item');
// Loop trough all menu items and attach
// event listeners.
for (var i = 0; i < menuItems.length; i++) {
// Check if element truely exsists
if (menuItems[i]) {
menuItems[i].addEventListener('click', function(e){
////////////////////////////////
// NOTE: i, is out of scope! //
//////////////////////////////
var icon = menuItems[i].children[1],
submenu = menuItems[i].children[2];
// Change icon color
if (icon.style.background !== "blue") {
icon.style.background = "blue";
} else {
icon.style.background = "red";
}
// Show/hide submenu
if (submenu.style.display !== "block") {
submenu.style.display = "block";
} else {
submenu.style.display = "none";
}
});
}
}