本文介绍了如何显示来自JavaScript数组/对象的图像?从第一个图像开始,然后点击下一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 <脚本> 
var images = ['/images/1.png','/images/2.png'];

函数buildImages(){
for(var i = 0; i< images.length; i ++){
document.createElement(images [i]);
}
}
< / script>

< / head>
< body>
< div onload =buildImages(); class =contentsid =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;

函数buildImage(){
var img = document.createElement('img')
img.src = images [index];
document.getElementById('content')。appendChild(img);
}

功能changeImage(){
变种IMG =的document.getElementById(内容)的getElementsByTagName( IMG)[0]
索引++。
index = index%images.length; //这是为了如果这是最后一张图像,那么首先转到图像
img.src = images [index];
}
< / script>

< body onload =buildImage();>
< div class =contentsid =content>< / div>
< button onclick =changeImage()> NextImage< / button>
< / body>

我不确定 div 有一个 onload 事件或不是,所以我称为 onload body。




Attempting to load images from my JavaScript array and display the first one the array. I then need to add a function that will allow the next image in the array to be displayed and so on till the end of the array.

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

Within the images array are paths to the images. They look like "server/images/05-08-2014-1407249924.png"

解决方案

See I did it like bellow

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

I was not sure div has an onload event or not so I called onload of body.

DEMO

这篇关于如何显示来自JavaScript数组/对象的图像?从第一个图像开始,然后点击下一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:00