我一直在努力完成分配给我的一项任务。
(iii)描述可用以处理交通灯序列的阵列的结构。
(iv)编写一个脚本,该脚本使用部分(iii)中描述的数组生成一组交通灯的动画,以便每次单击按钮时,信号灯在标准序列中发生变化。
这就是我所拥有的。
<!DOCTYPE html>
<html>
<body>
<img id="RedLight.png" onclick "changeImage()" src="RedLight.png" width="200" height="300">
<p>Traffic light animation.</p>
<button type="button" onclick="changeImage()">Change Lights</button>
<script>
function changeImage() {
var image = document.getElementById("RedLight.png");
if (image.src.match("RedLight.png")) {
image.src = "RedAmber.png";
} else if (image.src.match("RedAmber.png")) {
image.src = "GreenLight.png";
} else if (image.src.match("GreenLight.png")) {
image.src = "AmberLight.png";
} else {
image.src = "RedLight.png";
}
}
</script>
</body>
</html>我感到困惑的是:
这段代码是否使用数组?此外,数组的结构意味着什么?
谢谢你的帮助。
发布于 2016-11-26 14:46:27
这对我有用(点击广场):
针对您的情况的代码:
// Remember to include jQuery first!
function switchLight() {
var image = $('img');
//the array, but is useless and no sense in this case
var lightColor = ['GreenLight.png', 'AmberLight.png', 'RedLight.png']; // green orange red
switch ( image.src ) {
case lightColor[0]:
image.setAttribute('src', lightColor[1]);
break;
case lightColor[1]:
image.setAttribute('src', lightColor[2]);
break;
case lightColor[2]:
image.setAttribute('src', lightColor[0]);
break;
default: // else if not 0, 1 or 2
console.log('Light is off');
}
}通用片段:
// Remember to include jQuery first!
function switchLight() {
var color = $('#light').css('background-color');
//the array
var colors = ['rgb(0, 128, 0)', 'rgb(255, 165, 0)', 'rgb(255, 0, 0)'];
switch (color) {
case colors[0]:
$('#light').css('background-color', colors[1] )
$('button').css('color', colors[1]);
$('button').css('border-color', colors[1]);
console.log('light is now ' + color + '...');
break;
case colors[1]:
$('#light').css('background-color', colors[2])
$('button').css('border-color', colors[2]);
$('button').css('color', colors[2]);
console.log('light is now ' + color + '...');
break;
case colors[2]:
$('#light').css('background-color', colors[0])
$('button').css('color', colors[0]);
$('button').css('border-color', colors[0]);
console.log('light is now ' + color + '...');
break;
default:
console.log('Light is off');
}
}.box {
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
#light {
background-color: green;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" id="light" onclick="switchLight()"></div>
我建议先了解一下什么是数组,然后再问如何使用它!
https://stackoverflow.com/questions/40817984
复制相似问题