gpt4 book ai didi

javascript - 制作一个前进按钮和一个倒退数组?

转载 作者:行者123 更新时间:2023-11-30 12:46:59 24 4
gpt4 key购买 nike

我正在尝试使用第二个 html 按钮使数组向后移动,但由于某些原因我不能,此代码使 Div 可以根据需要多次更改颜色甚至相同的颜色。现在我的疑问是如何让它向后循环或减少一些如何?

   <head>

<title></title>
<style>#placeDiv{width:100px;height:100px;}</style>
</head>

<body>
<div id = "placeDiv">ok</div>
<button onclick="forward()">Forward</button>
<script>
var myArray = ["black","yellow","black","red","blue"];
var i = 0;
function forward(){
if(myArray.length <= i) i=0;

document.getElementById("placeDiv").style.backgroundColor = myArray[i++];
};
</script>
</body>

最佳答案

我已经添加了您通过 jsfiddle 链接询问的内容的完整正确实现。

HTML

  <div id = "placeDiv">ok</div>
<button onclick="forward()">Forward</button>
<button onclick="backward()">Backward</button>

JS

var myArray = ["black","yellow","green","red","blue"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
forward=function(){

if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}

document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){

if(i == 0)
{i=myArray.length-1;}
else
{
i=i-1;
}


document.getElementById("placeDiv").style.backgroundColor = myArray[i];


}

还有我有演示的 JSFiddle 链接

http://jsfiddle.net/96azU/1/

关于javascript - 制作一个前进按钮和一个倒退数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22204049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com