简体   繁体   English

从数组元素设置img标签的src属性

[英]Set the src attribute of img tag from an array element

I have an array 我有一个数组

pics = ["url1", "url2", "url3"]

I want want to be able to set the src attribute of an image to an array element like so: 我希望能够将图像的src属性设置为数组元素,如下所示:

<img src = pics[0]>

Problem is that html does not recognize that I am want the string element pic[0] not literally "pic[0]", so it throws an error 问题是html无法识别我是否想要字符串元素pic [0]而不是字面意义上的“ pic [0]”,因此会引发错误

Uncaught TypeError: Cannot set property 'src' of null 

Thanks 谢谢

You can't use JavaScript in arbitrary HTML attributes. 您不能在任意HTML属性中使用JavaScript。 You need to modify the DOM to add them afterwards. 您需要修改DOM以便随后添加它们。

 var img = document.createElement('img');
 img.alt = "Suitable alternative text";
 img.src = pics[0];
 document.getElementById('someElement').appendChild(img);

Make sure the script runs after someElement exists so it doesn't error on the last line. 确保脚本在someElement存在之后运行,以便在最后一行不会出错。

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

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