带有嵌套if/else语句的循环的javascript没有执行,不确定是什么'It’出了问题
javascript for loop with nested if/else statement not executing, not sure what's gone wrong
我正在为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;
}
}
}
相关文章:
- 框架的可用性问题是什么
- 我的图表出了什么问题?我使用的是谷歌图表api
- 有人能说出我的代码出了什么问题吗?我是个初学者
- 是什么导致了我的scrollTo函数出现问题
- 在这种情况下,正则表达式中的“[”是什么( 2 个问题)
- 我的变量有什么问题,它是未定义的
- 如果不是这样的话,这有什么问题
- 这个 JavaScript for loop 有什么问题?是定义条件的第二条语句吗?
- DB到JSP:解决数字格式问题的最佳方法是什么
- "class是一个保留的标识符“;我的javascript出了什么问题
- 这个问题的原因是什么;无法转换org.json.JSONArray类型的参数“”;在react原生android中
- 使用该系统进行网页布局的潜在问题是什么?
- 属性vs变量:性能问题是什么?
- 这个问题是什么,以及如何通过jquery自己的方式来防止
- 浏览器渲染网页的顺序是什么,为什么脚本阻塞是一个问题
- 有人能解释一下对象内部的数组是如何工作的吗?这段代码有什么问题?
- 使用canvas.toDataURL的安全问题是什么?
- 修复HTML布局问题的最好方法是什么?
- 使用Twitter Bootstrap (JS和Jquery)的下拉菜单不会下拉-这是什么问题?
- [Javascript]- removeEvenlistner不工作,是什么问题