如何显示阵列中的图像(用户控制的交通信号灯)

时间:2016-09-26 19:02:44

标签: javascript arrays image

<!-- 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 个答案:

答案 0 :(得分:0)

document.write()仅将HTML添加到文档的末尾。

要更改现有标记,您需要拥有一个更改“src”的事件处理程序。图像DOM节点的属性。

<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");' />