javascript - 如何将图片附加到数组的位置? javascript

标签 javascript arrays image

我正在创建一个能够在按下按钮时显示 5 个图像的脚本。 我需要在数组的位置插入 5 张图像,例如;

array [0] = image1; 
array [1] = image2; 

etc ... 

当用户按下“更改”按钮时,图像 1(显示在屏幕上)将被附加到数组第二个位置的第二个图像替换。

<style type="text/css">
#button1 
{
border:2px #333 solid;   
padding:20px;
width:250px;
-webkit-border-radius:40px;
-moz-border-radius:40px;
border-radius:40px;
}
</style>
<div align="center">
<br><br><br><br>
<img src="Koala.jpg" id="im1" width="300px" height="200px">
<img src="Casa.jpg" id="im1" width="300px" height="200px">
<img src="Tulipani.jpg" id="im1" width="300px" height="200px">
<img src="Pinguini.jpg" id="im1" width="300px" height="200px">
<img src="Deserto.jpg" id="im1" width="300px" height="200px">
<br><br>
<input type="button" id="button1" value="cambia" onclick="im()" height="50">
</div>
<script>

var array = new Array();

function im()
{
console.log("on");
}

</script> 

但是此代码显示所有 5 个图像。

到目前为止,我已经实现了 html 样式,但我不知道可以让我继续的方法或属性。你能帮我吗?

最佳答案

<img src="Deserto.jpg" id="im1" width="300px" height="200px">
<!-- only one <img>. And btw. never use the same id multiple times -->
<br><br>
<input type="button" id="button1" value="cambia" onclick="im()" height="50">

然后是 JavaScript:

 var
 current = 0,
 images = [];

 images.push('Koala.jpg');
 images.push('Casa.jpg');
 images.push('Tulipani.jpg');
 images.push('Pinguini.jpg');
 images.push('Deserto.jpg');


 function im() {
   current += 1;
   if (current >= images.length) {
     current = 0;
   }
   document.getElementById('im1').src = images[current];
 }

关于javascript - 如何将图片附加到数组的位置? javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23430689/

相关文章:

r - 将字符串变量分割成多个变量

php - 使用 PHP 通过表单向 MySQL 添加多行

image - 如何获取短语(轨道和专辑)的单个/第一张图像

javascript - 我想根据调用的函数来更改图像的鼠标悬停和鼠标悬停效果

javascript - 使用 JavaScript 根据分辨率为不同设备提供不同尺寸的图像

javascript - 查询。动画。大批。变量。选择器。下一个/上一个按钮

javascript - 如何在javascript中将base64编码的图像字符串发送到JSON对象?

javascript - 如何获取图像数组中的特定按钮 ID

javascript - 无法在javascript中获得 "\n"的效果

javascript - 将组合框中的第一个值设置为空