window.onload = function() {
// set default for landing page:
window.location.replace("#Overview");
// register click event listener for top navigation:
var navBarButtons = ["class1","class2","class3","class4","class5","class6","class7","class8","class9"];
var navBarTargets = ["id1","id2","id3","id4","id5","id6","id7","id8","id9"];
registerNavBar(navBarButtons, navBarTargets);
}
function registerNavBar(navBarButtons, navBarTargets){
for (var i=0; i<navBarButtons.length; i++){
sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
sourceElement.addEventListener("click",clickNavBarButton({targets:navBarTargets,index:i}))
}
}
function clickNavBarButton(event){
clearPages(event.targets);
document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
}
function clearPages(navBarTargets) {
for (i=0; i<navBarTargets.length; i++){
var target = "#".concat(navBarTargets[i]),classList=document.querySelector(target).classList;
if (classList.contains("active")){
classList.remove("active")
}
}
}
我试图向导航栏中的元素添加一个onclick事件,如下所示:
<div id="left_nav">
<a href="#Overview" title="Overview"><span class="class1"></span></a>
registerNavBar()函数无法将onclick事件添加到#left_nav .classn
选择器返回的元素中。
.active
类定义为
.active {
display: block!important
}
,而默认状态为
display: none
所以添加/删除.active类可以切换可见性。使用外部库不是一种选择。
目前循环中的所有函数都是在没有抛出错误的情况下执行的,我最终会显示带有#id9 beeing的元素,但按钮不会在单击时触发onclick事件。 如何正确地将eventListeners添加到Array中的所有元素?
答案 0 :(得分:1)
您可以创建closure以保留事件对象数据
function registerNavBar(navBarButtons, navBarTargets){
for (var i=0; i<navBarButtons.length; i++){
sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
sourceElement.addEventListener("click",clickNavBarButton({targets:navBarTargets,index:i}))
}
}
function clickNavBarButton(event){
return function(){
clearPages(event.targets);
document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
}
}