简体   繁体   English

如何获取图像src作为变量并显示数组中的图像?

[英]How to get the image src as a variable and display an image from an array?

I am currently creating an image gallery to work on my skills. 我目前正在创建一个图片库,以提高自己的技能。

I have an array that consists of images that I have from a folder called 'images'. 我有一个数组,其中包含来自名为“ images”的文件夹中的图像。

I have an image that has an id of 'imgsrc' with an empty source on my HTML page, so it's not displaying anything. 我的HTML页面上有一个ID为'imgsrc'且源为空的图像,因此不显示任何内容。 I would like to be able to have access to the first image in my 'images' folder and display it as the source for my image using Javascript. 我希望能够访问“图像”文件夹中的第一张图像,并使用Javascript将其显示为图像的源。

Here is what I tried to do: 这是我尝试做的事情:

var images = ['images/1.jpg', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg','images/7.jpg', 'images/8.jpg', 'images/9.jpg'];

var imgsrc = document.getElementById('imgsrc').src;

var index = 0;

imgsrc = images[index];

Here is my HTML : 这是我的HTML:

<section class="gallery">

  <img id='imgsrc' src="">

</section>

What should I do ? 我该怎么办 ?

I appreciate all responses 我感谢所有回应

The problem is that imgsrc stores the string value and not a reference to the image src. 问题在于imgsrc存储字符串值,而不是对图像src的引用。 Edit it directly: 直接编辑:

 var images = ['images/1.jpg', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg','images/7.jpg', 'images/8.jpg', 'images/9.jpg']; var index = 0; console.log(document.getElementById('imgsrc').src); document.getElementById('imgsrc').src = images[index]; console.log(document.getElementById('imgsrc').src); 
 <section class="gallery"> <img id='imgsrc' src=""> </section> 

var images = ['images/1.jpg', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg','images/7.jpg', 'images/8.jpg', 'images/9.jpg'];

var imgsrc = document.getElementById('imgsrc');

var index = 0;

imgsrc.setAttribute('src',images[index]);

Try to use setAttribute() . 尝试使用setAttribute()

Works with Minimum Code !!! 使用最小代码!

  <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <section class="gallery"> <img alt="sd" id='imgsrc' src=""> </section> <script> var images = ['http://i65.tinypic.com/zl2rfr.jpg', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg','images/7.jpg', 'images/8.jpg', 'images/9.jpg']; var index = 0; document.getElementById("imgsrc").src = images[index]; </script> </body> </html> 

** **

Get the element then set its src 获取元素,然后设置其src

var images = ['images/1.jpg', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg','images/7.jpg', 'images/8.jpg', 'images/9.jpg'];
var imgsrc = document.getElementById('imgsrc');// get element
var index = 0;
imgsrc.src = images[index];
console.log(imgsrc.src);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM