2016-06-27 215 views
-2

當我嘗試運行腳本時,如果按下按鈕時會改變燈光,則不會顯示任何內容,圖像甚至不會顯示。我可以修復的任何方式?使用按鈕單擊,更改圖像

下面是代碼:

<!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

你認爲「如果list = 0」在做什麼?你如何看待這段代碼決定使用哪些If語句? – master565

+0

將您的腳本標籤放在文檔的中。 –

+0

img標記錯誤 – Atula

回答

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

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); 

您還需要另一個變量來跟蹤您顯示的值的索引,以便您可以增加到下一個圖像。