为什么不在HTML准备好后就直接迭代图像呢?只需将一个侦听器附加到
DOMContentLoaded
事件:
document.addEventListener('DOMContentLoaded', () => {
let images = [...document.querySelectorAll('img[alt]')]
for (const image of images) {
const altDiv = document.createElement('div')
altDiv.textContent = image.getAttribute('alt')
image.parentNode.appendChild(altDiv)
}
})
<div>
<img src="http://lorempixel.com/200/200/" alt="my beautiful alt text" />
</div>
<div>
<img src="http://lorempixel.com/200/100/" alt="my beautiful alt text 2" />
</div>
如果要确保在显示alt文本之前加载图像,请在
load
document.addEventListener('DOMContentLoaded', () => {
let images = [...document.querySelectorAll('img[alt]')]
for (const image of images) {
image.addEventListener('load', (e) => {
const altDiv = document.createElement('div')
altDiv.textContent = image.getAttribute('alt')
image.parentNode.appendChild(altDiv)
})
}
})
<div>
<img src="http://lorempixel.com/200/200/" alt="my beautiful alt text" />
</div>
<div>
<img src="http://lorempixel.com/100/200/" alt="my beautiful alt text 2" />
</div>
<div>
<img src="http://lorempixel.com/200/100/" alt="my beautiful alt text 3" />
</div>