[英]javascript for loop with nested if/else statement not executing, not sure what's gone wrong
I'm working on this little function for a Hype web animation. 我正在为Hype网络动画开发此小功能。 Basically, I have between 2 and 8 or so menu items, and when one is clicked, it has to become slightly less opaque and the previous one has to become opaque again.
基本上,我有2到8个左右的菜单项,当单击一个菜单项时,它必须变得不透明一些,而上一个菜单项必须再次变得不透明。 I have a variable that is set to the most recently clicked element id, and another that is set to the class of elements that the menu items are in using getElementIdByClassName.
我有一个变量,它设置为最近单击的元素ID,另一个变量是设置为菜单项使用getElementIdByClassName的元素的类。 The for loop iterates over the id's in the classes, and an if/else says "if colors[i].id != currentColor set opacity to 1; else set opacity to .3", or at least I think it says that.
for循环遍历类中的id,而if / else则说“ if colors [i] .id!= currentColor将不透明度设置为1;否则将不透明度设置为.3”,或者至少我认为是这样。 can anyone lend a hand on this?
有人可以帮忙吗? i can't seem to figure it out.
我似乎无法弄清楚。
Thanks! 谢谢!
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;
}
}
}
What is wrong with your code and how to fix. 您的代码有什么问题以及如何解决。
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;
Doesn't give you an array. 没有给你一个数组。
try 尝试
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.