通过设置内部HTML循环

时间:2016-08-10 21:18:42

标签: javascript arrays

我只能使用JavaScript来解决问题。我试着写一个for循环,但是在悬停时我得到了不确定。我基本上有一个动态生成的子菜单。当li在子菜单上盘旋时,内部HTML将被设置为更改为lis右侧的内容区域。

sideCol.getElementsByTagName('li')[0].addEventListener('mouseover', function(){
    document.getElementsByClassName('categoryExplorer-content')[0].children[2].innerHTML = document.getElementsByClassName('categoryExplorer-content')[0].children[1].innerHTML;
});
sideCol.getElementsByTagName('li')[1].addEventListener('mouseover', function(){
    document.getElementsByClassName('categoryExplorer-content')[0].children[2].innerHTML = document.getElementsByClassName('categoryExplorer-content')[1].children[1].innerHTML;
});
sideCol.getElementsByTagName('li')[2].addEventListener('mouseover', function(){
    document.getElementsByClassName('categoryExplorer-content')[0].children[2].innerHTML = document.getElementsByClassName('categoryExplorer-content')[2].children[1].innerHTML;
});
sideCol.getElementsByTagName('li')[3].addEventListener('mouseover', function(){
    document.getElementsByClassName('categoryExplorer-content')[0].children[2].innerHTML = document.getElementsByClassName('categoryExplorer-content')[3].children[1].innerHTML;
});
sideCol.getElementsByTagName('li')[4].addEventListener('mouseover', function(){
    document.getElementsByClassName('categoryExplorer-content')[0].children[2].innerHTML = document.getElementsByClassName('categoryExplorer-content')[4].children[1].innerHTML;
});

2 个答案:

答案 0 :(得分:1)

循环非常简单,只需使用局部变量(ix)。

var count = sideCol.getElementsByTagName('li').length;
for(var i=0;i<count;i++) {
    (function(ix) {
        sideCol.getElementsByTagName('li')[ix]
            .addEventListener('mouseover', function() {
                document.getElementsByClassName('categoryExplorer-content')[0]
                    .children[2].innerHTML = 
                document.getElementsByClassName('categoryExplorer-content')[ix]
                    .children[1].innerHTML;
        });
    })(i);
}

答案 1 :(得分:1)

使用forEach()循环遍历元素并绑定事件侦听器。然后,这将为索引提供一个闭包变量,您可以在处理函数中使用它来访问相应的元素。

[].forEach.call(sideCol.getElementsByTagName('li'), function(el, i) {
    el.addEventListener('mouseover', function() {
        var explorers = document.getElementsByClassName('categoryExplorer-content');
        explorers[0].children[2].innerHTML = explorers[i].children[1].innerHTML;
    });
});