带有嵌套if/else语句的循环的javascript没有执行,不确定是什么'It’出了问题

javascript for loop with nested if/else statement not executing, not sure what's gone wrong

本文关键字:是什么 问题 不确定 It 执行 else if 嵌套 语句 循环 javascript      更新时间:2023-09-26

我正在为Hype网络动画开发这个小函数。基本上,我有2到8个左右的菜单项,当一个菜单项被点击时,它必须变得稍微不那么不透明,前一个菜单必须再次变得不透明。我有一个变量设置为最近单击的元素id,另一个变量使用getElementIdByClassName设置为菜单项所在的元素类。for循环在类中的id上迭代,if/else说"if-colors[i].id!=currentColor将不透明度设置为1;else将不透明度设为.3",或者至少我认为它是这么说的。有人能帮忙吗?我好像想不通。

谢谢!

  changeShoe(hypeDocument, element, event){ 
        var currentColor = element.id;
        var colors = document.getElementsByClassName("colors").id;
         for (i = 0, n = colors.length; i<n; i++) {
                if(colors[i] !== currentColor){
                    colors[i].style.opacity = 1;
                    }
                else{
                    colors[i].style.opacity = .3;
                    }
            }
    }

您的代码有什么问题以及如何修复。

changeShoe(hypeDocument, element/*, event*/){ //event is not used and can be removed from parameters
    var currentColor = element.id;//This is good
    //var colors = document.getElementsByClassName("colors").id;
    //document.getElementsByClassName("colors") is a HTMLCollection and doesn't have **id** property
    //it means colors is undefined
    var colors = document.getElementsByClassName("colors");// this way
     for (i = 0, n = colors.length; i<n; i++) {//good approach
            //colors is now collection and colors[i] is HTML element. So .id
            //if(colors[i].id !== currentColor){//this is OK IIF each element has unique ID
            if(colors[i] !== element){//not exact match
                colors[i].style.opacity = 1;//now it is correct
                }
            else{
                colors[i].style.opacity = .3;
                }
        }
}
document.getElementsByClassName("colors").id;

不会给你一个数组。

尝试

changeShoe(hypeDocument, element, event){ 
    var currentColor = element.id;
    var colors = document.getElementsByClassName("colors");
     for (i = 0, n = colors.length; i<n; i++) {
            if(colors[i].id !== currentColor){
                colors[i].style.opacity = 1;
                }
            else{
                colors[i].style.opacity = .3;
                }
        }
}