当我尝试运行一个脚本,当我按下按钮时会改变灯光,没有任何反应,图像甚至都没有显示。我能解决什么方式吗?
以下是代码:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="IMG" src=N:\Year 10\Computing\Exam\A452 Practical Exam\Interactive Buttons\>
<button type="button" onclick="changeLights()">Change Lights</button>
<script>
var list=[];
list[0] = '<img src="N:\Year 10\Computing\Exam\A452 Practical Exam\Interactive Buttons\red.jpg" width="254"height="501" alt="Traffic Light Red">';
list[1] = '<img src="N:\Year 10\Computing\Exam\A452 Practical Exam\Interactive Buttons\green.jpg" width="249" height="494" alt="Traffic Light Yellow">';
list[2] = '<img src="N:\Year 10\Computing\Exam\A452 Practical Exam\Interactive Buttons\yellow.jpg" width="243" height="506" alt="Traffic Light Green">';
function changeLights() {
var list = document.getElementById('IMG');
if list=0 {
image.src='<img src="N:\Year 10\Computing\Exam\A452 Practical Exam\Interactive Buttons\red.jpg" width="254"height="501" alt="Traffic Light Red">';
} else if list=1 {
image.src=1;
} else if list=2 {
image.src=2;
}
</script>
</body>
</html>
答案 0 :(得分:0)
<img id="IMG" src="N:\Year 10\Computing\Exam\A452 Practical Exam\Interactive Buttons"\>
括号!
仅更改src,而不是整个html对象:
document.getElementById("IMG").src="change.png";
- 使用相对路径,与html文件相同的文件夹。不要使用资源管理器路径xD
答案 1 :(得分:0)
这看起来像是作业!
您对如何在Javascript中访问数组的理解存在缺陷。请看下面的例子。
var list = [];
// Assign some values
list[0] = "Fred";
list[1] = "Wilma";
list[2] = "Barney";
list[3] = "Betty";
// Check the length of the array
alert(list.length);
// Iterate over the array outputting the values.
for(i=0; i<list.length; i++)
alert(list[i]);
// Access values directly
var sentance = list[0] + " is married to " + list[1] + " and " + list[2] + " is married to " + list[3] + ".";
alert(sentance);
您还需要另一个变量来跟踪您正在显示的值的索引,以便您可以增加到下一张图像。