我有这两个 javascript 函数,由于某种原因,我必须单击按钮两次才能让它们工作。有什么想法吗?
var shirts = new Array("shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png");
var index = 0;
function changecolor(){
if (index > 4){
index = 0;
}
var shirtpick = document.getElementById("shirt");
shirtpick.setAttribute('src',shirts[index]);
index++;
}
其他功能:
function changecolorback(){
index--;
i++;
if (index < 0){
index = 4;
}
var shirtback = document.getElementById("shirt");
shirtback.setAttribute('src',shirts[index]);
}
最佳答案
var shirts = ["shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png"],
index = 0;
function changecolor(amount){
index = (index + amount) % shirts.length;
document.getElementById("shirt").setAttribute('src',shirts[index]);
}
原因是您的增量:
您在代码执行后递增(在一个函数中,但不在另一个函数中,因此您的 changecolorback()
应该表现良好)。
您还有看起来多余的 i++
,以及一些仅使用一次的变量。
我(大幅)缩短了您的代码,因此您无需过多滚动即可看到这些注释。
您现在可以直接执行 changecolor(-1)
,而不是调用 changecolorback()
,前向方法是 changecolor(1)
。
另一个优点是,这将允许您跳跃多个或随机数量,这可能(或可能没有)有用。
编辑:
JS 像 Java 一样实现模数,因此负数仍然保留其符号。 IE。 (-1)%5 === -1
您可以通过更改轻松克服这个问题(更优雅,但不完全等效):
index = Math.abs(index + amount) % shirts.length;
或
index = ((index + amount) % shirts.length + shirts.length ) % shirts.length;
关于javascript函数需要双击才能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6022375/