【发布时间】:2017-04-18 13:33:25
【问题描述】:
我正在尝试创建一个程序,该程序使用一组函数来循环执行顺序。我已经包含了下面的程序,有人可以建议我做错了什么。我在 HTML 上创建了一组交通信号灯,我正在尝试编写一些 javascript 来更改单击按钮时显示的灯。我创建了一组函数来确定我希望灯光出现的顺序。我还编写了将显示每个灯光的函数。我是 javascript 新手,任何帮助将不胜感激。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Task three</title>
<link href="Task 3-CSS.css" rel="stylesheet" type="text/css" />
<script src="Task3-Java.js"></script>
</head>
<body>
<div id="control_panel">
<button onclick="change_light">Change Light</button>
</div>
<div id="traffic_light">
<div id="red_light" class="light"></div>
<div id="amber_light" class="light"></div>
<div id="green_light" class="light"></div>
</div>
</body>
</html>
var light_array=[red,red_amber,green,amber];
var light_index = 0;
function no_light(){
document.getElementById('red_light').style.backgroundColor = "black";
document.getElementById('amber_light').style.backgroundColor = "black";
document.getElementById('green_light').style.backgroundColor = "black";
}
function red(){
no_light();
document.getElementById('red_light').style.backgroundColor="red";
}
function red_amber(){
no_light();
document.getElementById('red_light').style.backgroundColor="red";
document.getElementById('amber_light').style.backgroundColor="orange";
}
function green(){
no_light();
document.getElementById('green_light').style.backgroundColor="green";
}
function amber(){
no_light();
document.getElementById('amber_light').style.backgroundColor="orange";
}
function change_light(){
light_array[light_index](red,red_amber,green,amber);
light_index++;
if (light_index > 3){light_index = 0;}
}
change_light();
【问题讨论】:
-
您能告诉我们您遇到了什么问题吗?你有错误吗?
-
您应该更改标签,因为这与 Java 无关。 Java 和 Javascript 完全不同。
-
我总是想知道为什么不那么复杂的不完整问题会在发布后的几秒钟内获得投票。
-
我建议您添加相关的 HTML 并使其成为 Stack Snippet,这样我们就可以在您的问题中测试您的代码 - 查看关于 minimal reproducible example 的章节。此外,您忘记真正解释如何您的代码无法正常工作或无法达到您的预期。
-
我投了赞成票,可以吗? :) 对我来说,它非常完整并且清楚 OP 的问题所在。
标签: javascript arrays function