function toggle() {
overlays = document.getElementsByClassName("overlay");
if (globalOpacityValue == 0.9){
globalOpacityValue = 0;
}else{
globalOpacityValue = 0.9;
}
console.log("globalOpacityValue: " + globalOpacityValue);
for (overlay in overlays) {
overlays[overlay].style.opacity = globalOpacityValue;
}
console.log("toggle routine done!");
tempStoreOnChangeArtificial();
console.log("tempStoreOnChangeArtificial done!");
}
在我看来,在for / in循环之后,我的函数结束了。
我的toggle()从不显示“切换例程已完成!”,显然它不会运行tempStoreOnChangeArtificial();
但是它在for / in循环中做了一些事情。
为什么?
答案 0 :(得分:2)
document.getElementsByClassName
返回一个像object这样的数组,它不能用for ... in
statement进行迭代。
function toggle() {
var overlays = document.getElementsByClassName("overlay"),
i;
if (globalOpacityValue == 0.9){
globalOpacityValue = 0;
}else{
globalOpacityValue = 0.9;
}
console.log("globalOpacityValue: " + globalOpacityValue);
for (i = 0; i< overlays.length; i++) {
overlays[i].style.opacity = globalOpacityValue;
}
console.log("toggle routine done!");
// tempStoreOnChangeArtificial();
console.log("tempStoreOnChangeArtificial done!");
}
var globalOpacityValue = 0;
toggle();
&#13;
<div class="overlay">a</div>
<div class="overlay">b</div>
<div class="overlay">c</div>
&#13;
答案 1 :(得分:1)
HTMLCollection
从in
获取元素。overlay of overlays
。function toggle() {
overlays = document.getElementsByClassName("overlay");
if (globalOpacityValue == 0.9){
globalOpacityValue = 0;
}else{
globalOpacityValue = 0.9;
}
console.log("globalOpacityValue: " + globalOpacityValue);
for (overlay of overlays) {
overlay.style.opacity = globalOpacityValue;
}
console.log("toggle routine done!");
tempStoreOnChangeArtificial();
console.log("tempStoreOnChangeArtificial done!");
}
答案 2 :(得分:1)
我不知道您可以使用document.getElementByClassName
迭代for in
也许就是问题所在,您可能想要迭代HTMLCollection,如下所示:
function toggle() {
overlays = document.getElementsByClassName("overlay");
if (globalOpacityValue == 0.9){
globalOpacityValue = 0;
}else{
globalOpacityValue = 0.9;
}
console.log("globalOpacityValue: " + globalOpacityValue);
Array.prototype.forEach.call(overlays, function(overlay) {
overlay.style.opacity = globalOpacityValue;
});
console.log("toggle routine done!");
tempStoreOnChangeArtificial();
console.log("tempStoreOnChangeArtificial done!");
}