2016-06-20 75 views
0
<!DOCTYPE html> 
<html> 
<head> 
<title>Controlled Assessment!</title> 
<link rel="stylesheet" href="Css/stylesheet.css" type="text/css"/> 
<!-- This is the webpage i found how to link an external script http://stackoverflow.com/questions/13739568/how-do-i-link-a-javascript-file-to-a-html-file --> 
</head> 

<body> 

    <img id="color" src="Pictures/green.jpg" > 

    <p id="hel">he</p> 

    <button onclick="nxt()">new colour</button> 

    <script type="text/jscript" src="JavaScript/trafficlight.js" /> 
</body> 


<footer> 

    <script src="JavaScript/trafficlight.js"></script> 

</footer> 


</html> 

這是我的html代碼Javascript數組,圖像鏈接,鏈接

//My array that will be used for the traffic light sequence 
var colour = ["Pictures/red.jpg", "Pictures/green.jpg", "Pictures/amber.jpg"]; 

function nxt() { 

"use strict"; 
document.getElementById("hel").innerHTML = "helllll"; 

document.getElementById("color").innerHTML = colour["Pictures/red.jpg"]; 
} 

這是我的Javascript,當你點擊按鈕圖像更改爲不同的圖像而這正是我試圖做的是在這個例子中的JavaScript部分列出的數組即時試圖從綠色變爲紅色,但它不工作,我真的很困惑,爲什麼?

+0

您可以通過修改'src'屬性,而不是'innerHTML'改變圖像。 –

回答

1

要更改圖像的src,請執行以下操作: document.getElementById(「color」)。src = color [0];

此外,你有顏色[「圖片/ red.jpg」]這沒有多大意義。 按你想要的元素的id來查找它。

//My array that will be used for the traffic light sequence 
 
var colour = ["Pictures/red.jpg", "Pictures/green.jpg", "Pictures/amber.jpg"]; 
 

 
function nxt() { 
 
document.getElementById("hel").innerHTML = "helllll"; 
 

 
document.getElementById("color").src = colour[0]; 
 
}
<img id="color" src="Pictures/green.jpg" > 
 

 
    <p id="hel">he</p> 
 

 
    <button onclick="nxt()">new colour</button>