2016-09-26 40 views
-2
<!-- I set the tags here--> 
<!DOCTYPE html> 
<html> 
<head> 
    <!-- I set the coding language--> 
    <script type="text/javascript"> 
    <!-- 
    <!-- The image variables can be seen here--> 
    var TrafficLights = new array() 
    image[0] = "traffic-light-red.jpg"; 
    image[1] = "traffic-light-red-amber.jpg"; 
    image[2] = "traffic-light-green.jpg"; 
    image[3] = "traffic-light-amber.jpg"; 

    <!--they are then put into an array--> 
    var TrafficLightImages = [image1, image2, image3, image4] 

    <!-- I close the script and head tags--> 
    </script> 
</head> 
<!-- I start a body tag--> 

<body> 
    <!-- Create a button with the button class= "myButton" and name it to say 
     "Change the lights!"--> 
    <!-- It will also change the image of the traffic light--> 
    <button class="myButton" onclick="slideit()">Change the lights!</button> 

    <!-- I call the URL of the image and I set its width and length to 120 and 270 
<img src="traffic-light-red.jpg" name="slide" width="152" height="320"> 

<!-- I set the coding language--> 
    <script type="text/javascript"> 
    <!-- 
    <!-- I create another variable that makes step=1--> 
    var step = 1; 
    var i = 0 
     <!--Previously this was a do/while loop but I changed as I learnt it was the 
      source of my previous problem--> 
     <!-- I create a function names slide--> 

    function UpdateImage() { 
     for (i = 0; i < TrafficLights.length; i++) { <!-- Change this --> 

      document.write("<li><img src='" + TrafficLights[i] + "'width=" 
      150 " height=" 
      110 "/>span>" + TrafficLights[i] + "</span><li>"); 


      //--> 
    </script> 
</body> 
</html> 

上面的代碼是代碼。如何通過陣列中不同的紅綠燈圖像進行旋轉,顯示它們並只在按下按鈕時更改圖像。如何顯示陣列中的圖像(用戶控制的交通信號燈)

如果可能,請顯示完整的工作腳本。

+1

起初image1 does not exist,圖片[1]沒有 –

+1

偏離主題,但值得一提。你的評論過多,他們讓你的代碼更難閱讀。 – Mihailo

+1

其中是slideit()方法? – atul

回答

0

document.write()僅將HTML添加到文檔的末尾。

要更改現有標記,您需要具有更改圖像DOM節點的「src」屬性的事件處理程序。

<script> 
function changeImage(image_name) { 
    var img = document.getElementById("image_id"); 
    img.src = image_name; 
} 
</script> 

<img src='placeholder.png' id='image_id' /> 
<input type='button' value='Set Green' onClick='changeImage("traffic-light-green.jpg");' /> 
<input type='button' value='Set Red' onClick='changeImage("traffic-light-red.jpg");' />