我在javascript中使用简单的循环有一个小问题,无法解决问题!我错过了什么?
window.onload = function(){
var linksToSlides = ["fischer","neotex","felo","safety","stella","boltsNuts"];
for (var i=0;i < 6;i++){
document.getElementsByClassName("headerSlideTo")[i].addEventListener("click", function(){ goTo(linksToSlides[i]); });
document.getElementsByClassName("footerSlideTo")[i].addEventListener("click", function(){ goTo(linksToSlides[i]); });
document.getElementsByClassName("menuLinks")[i].addEventListener("click", function(){ closeMenu();goTo(linksToSlides[i]); });
}
};
它根本不起作用......但是下面的代码没有循环。
window.onload = function(){
var linksToSlides = ["fischer","neotex","felo","safety","stella","boltsNuts"];
//header links to slides
document.getElementsByClassName("headerSlideTo")[0].addEventListener("click", function(){goTo(linksToSlides[0]);});
document.getElementsByClassName("headerSlideTo")[1].addEventListener("click", function(){goTo(linksToSlides[1]);});
document.getElementsByClassName("headerSlideTo")[2].addEventListener("click", function(){goTo(linksToSlides[2]);});
document.getElementsByClassName("headerSlideTo")[3].addEventListener("click", function(){goTo(linksToSlides[3]);});
document.getElementsByClassName("headerSlideTo")[4].addEventListener("click", function(){goTo(linksToSlides[4]);});
document.getElementsByClassName("headerSlideTo")[5].addEventListener("click", function(){goTo(linksToSlides[5]);});
//footer links to slides
document.getElementsByClassName("footerSlideTo")[0].addEventListener("click", function(){goTo(linksToSlides[0]);});
document.getElementsByClassName("footerSlideTo")[1].addEventListener("click", function(){goTo(linksToSlides[1]);});
document.getElementsByClassName("footerSlideTo")[2].addEventListener("click", function(){goTo(linksToSlides[2]);});
document.getElementsByClassName("footerSlideTo")[3].addEventListener("click", function(){goTo(linksToSlides[3]);});
document.getElementsByClassName("footerSlideTo")[4].addEventListener("click", function(){goTo(linksToSlides[4]);});
document.getElementsByClassName("footerSlideTo")[5].addEventListener("click", function(){goTo(linksToSlides[5]);});
//menu links to slides
document.getElementsByClassName("menuLinks")[0].addEventListener("click", function(){closeMenu();goTo(linksToSlides[0]);});
document.getElementsByClassName("menuLinks")[1].addEventListener("click", function(){closeMenu();goTo(linksToSlides[1]);});
document.getElementsByClassName("menuLinks")[2].addEventListener("click", function(){closeMenu();goTo(linksToSlides[2]);});
document.getElementsByClassName("menuLinks")[3].addEventListener("click", function(){closeMenu();goTo(linksToSlides[3]);});
document.getElementsByClassName("menuLinks")[4].addEventListener("click", function(){closeMenu();goTo(linksToSlides[4]);});
document.getElementsByClassName("menuLinks")[5].addEventListener("click", function(){closeMenu();goTo(linksToSlides[5]);});
};
我还运行了测试,看到[i]
值正确显示,linksToSlides[i]
正在给出好的值,而且一切似乎都很好。
其他函数中的所有其他循环都可以正常工作。只是这个循环不起作用!