本文共 736 字,大约阅读时间需要 2 分钟。
I had the need to programmatically add an image to the , in other words to an HTML page, dynamically.
我需要以编程方式动态地将图像添加到 ,即添加到HTML页面。
To do that, I created an img
element using the createElement
method of the Document object:
为此,我使用Document对象的createElement
方法创建了一个img
元素:
const image = document.createElement('img')
Then I set the src
attribute of the image:
然后设置图像的src
属性:
image.src = '/picture.png'
(You can use a relative or an absolute URL, just as you’d use in a normal HTML img
tag)
(您可以使用相对或绝对URL,就像在普通HTML img
标签中使用的一样)
Then I identified the container I wanted to append the image to, and I called the appendChild()
method on it:
然后,我确定了要将图像附加到的容器,并在其上调用了appendChild()
方法:
document.querySelector('.container').appendChild(image)
翻译自:
转载地址:http://nomgb.baihongyu.com/