Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 点击按钮的无限循环_Javascript_Loops - Fatal编程技术网

Javascript 点击按钮的无限循环

Javascript 点击按钮的无限循环,javascript,loops,Javascript,Loops,我被要求创建一个交通灯,每个按钮按下后切换到下一个灯。我不知道如何实现无限循环 我知道有一种非常有效的方法可以做到这一点,但我的代码只是为了给出我想要的结果的想法 button.onclick=函数(){ red.style.display=“block”; yellow.style.display=“无”; green.style.display=“无” button.onclick=函数(){ red.style.display=“无”; yellow.style.display=“blo

我被要求创建一个交通灯,每个按钮按下后切换到下一个灯。我不知道如何实现无限循环

我知道有一种非常有效的方法可以做到这一点,但我的代码只是为了给出我想要的结果的想法

button.onclick=函数(){
red.style.display=“block”;
yellow.style.display=“无”;
green.style.display=“无”
button.onclick=函数(){
red.style.display=“无”;
yellow.style.display=“block”;
green.style.display=“无”
button.onclick=函数(){
red.style.display=“无”
yellow.style.display=“无”;
green.style.display=“block”;
}
}

}
不使用静态定义,您可以使用元素创建一个数组,并通过在数组中使用当前显示的元素的索引来跟踪当前显示的元素,然后单击按钮时,迭代到下一个索引并隐藏上一个索引

let current=0;
恒光=[
document.getElementById(“红色”),
document.getElementById(“橙色”),
document.getElementById(“绿色”)
];
const button=document.getElementById(“迭代”);
button.onclick=函数(){
灯光[当前].style.display=“无”;
电流++;
如果(当前==灯光长度)
电流=0;
灯光[当前].style.display=“块”;
};
div{
显示:无;
宽度:50px;
高度:50px;
边界半径:50%;
}
#红色的{
显示:块;
背景:红色;
}
#橙色的{
背景:橙色;
}
#绿色的{
背景:绿色;
}
迭代

while(true)
。是一个基本循环,或者说是
时的循环。如果可能的话,你应该发布完整的代码。@mplungjan-我真希望我能(有意义地)提高人们寻找重复代码的努力。:-)(不知道我的大脑到底在哪里发布答案。)@mplungjan-啊,我明白了。关键是要显示逻辑,而不是UI。如果你制作一个代码片段,就要制作一个需要3盏灯的屏幕
currentActive = 1 //value should be 1 /2 / 3 and make sure this is a global variable
setTimeout(() => {
  // make sure red, yellow and green variable is properly defined here, 
  // call this after defining these variables by document.getElementById() 
  red.style.display = currentActive == 1 ? "block" : 'none';
  yellow.style.display = currentActive == 2 ? "block" : 'none';
  green.style.display = currentActive == 3 ? "block" : 'none';

  currentActive++; //increase for the next to occour
  currentActive = currentActive % 3; // mod by 3 so to run between 1,2,3
}, 1000)

//here using 1000 milisecond use your desire time as delay