我有这两个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++;
}
Run Code Online (Sandbox Code Playgroud)
其他功能:
function changecolorback(){
index--;
i++;
if (index < 0){
index = 4;
}
var shirtback = document.getElementById("shirt");
shirtback.setAttribute('src',shirts[index]);
}
Run Code Online (Sandbox Code Playgroud)
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]);
}
Run Code Online (Sandbox Code Playgroud)
原因是你的增量:你在代码执行后递增(在一个函数中,但在另一个函数中没有,所以你changecolorback()应该表现得很好).
你也i++看起来多余了,有些变量只用了一次.
我缩短了你的代码(大幅度),所以你可以在没有太多滚动的情况下得到这些评论.changecolorback()你现在可以做changecolor(-1),而不是打电话,前进的方法是changecolor(1).
另一个优点是,这将允许您跳过多个或随机数量,这可能(或可能不)有用.
编辑:
JS实现了像Java这样的模数,因此负面信息仍然存在.即(-1)%5 === -1
您可以通过更改(更优雅但不完全相同)轻松克服这个问题:
index = Math.abs(index + amount) % shirts.length;
Run Code Online (Sandbox Code Playgroud)
要么
index = ((index + amount) % shirts.length + shirts.length ) % shirts.length;
Run Code Online (Sandbox Code Playgroud)