如何从JavaScript数组/对象显示图像?从第一个图像开始,然后点击到下一个

How to display images from a JavaScript array/object? Starting with the first Image then onclick to the next

本文关键字:图像 然后 开始 下一个 第一个 数组 JavaScript 对象 显示 显示图      更新时间:2023-09-26

尝试从JavaScript数组中加载图像并在数组中显示第一个图像。然后,我需要添加一个函数,允许在数组中显示下一个图像,依此类推,直到数组结束。

<script>
var images = [ '/images/1.png', '/images/2.png' ];
function buildImages() {
    for (var i = 0; i < images.length; i++) {
        document.createElement(images[i]);
    }
}
</script>
</head>
<body>
    <div onload="buildImages();" class="contents" id="content"></div>
</body>

在images数组中是指向图像的路径。它们看起来像"server/images/05-08-2014-1407249924.png"

看我是怎么做的

<script>
    var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
    var index = 0;
    function buildImage() {
      var img = document.createElement('img')
      img.src = images[index];
      document.getElementById('content').appendChild(img);
    }
    function changeImage(){
      var img = document.getElementById('content').getElementsByTagName('img')[0]
      index++;
      index = index % images.length; // This is for if this is the last image then goto first image
      img.src = images[index];
    }
</script>
<body onload="buildImage();">
    <div class="contents" id="content"></div>
    <button onclick="changeImage()">NextImage</button>
</body>

我不确定div是否有onload事件,所以我调用了body的onload

// the container
var container = document.getElementById('content');
for (var i = 0; i < images.length; i++) {
    // create the image element
    var imageElement = document.createElement('img');
    imageElement.setAttribute('src', images[i]);
    // append the element to the container
    container.appendChild(imageElement);
}

有关如何执行DOM操作/创建的更多信息,请参阅MDN和其他资源。这些会对你的发展有很大帮助。

JSFiddle

    <body>
<img id="thepic"/>
<input type="button" id="thebutt" value="see next"/>
<script>
(function (){
        var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
        var imgcnt = 1;
        function changeIt() {
          if(imgcnt<images.length){
          document.getElementById("thepic").src=images[imgcnt++];
          } else{
          console.log("done")
          }
        }
        document.getElementById("thepic").src=images[0];
        document.getElementById("thebutt").onclick=changeIt;
        })();
        </script>
</body>
相关文章: