我只能使用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;
});

最佳答案

循环非常简单,只需使用局部变量(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);
}

08-15 18:42