首页 > 解决方案 > 循环只返回一个元素

问题描述

我需要遍历图像以获取所有图像的 Alt 属性,但代码仅返回第一张图像

const tagged = {
    getImgsAttributes: () => {
        const imgs = document.querySelectorAll('main img')
        for(let i = 0; i < imgs.length; i++) {
            const allAttributes = imgs[i].getAttribute('alt')
            return allAttributes
        }
    }
}

console.log(tagged.getImgsAttributes())

标签: javascriptdom

解决方案


您需要使用push()方法将每个 alt 属性值存储在一个空数组变量中。

const tagged = {
  getImgsAttributes: () => {
    var storing = [];
    const imgs = document.querySelectorAll('main img');
    for(let i = 0; i < imgs.length; i++) {
      const allAttributes = imgs[i].getAttribute('alt')
      storing.push(allAttributes);
    }
    return storing;
  }
}
console.log(tagged.getImgsAttributes())
<main>
  <img src="https://i.stack.imgur.com/fcbpv.jpg?s=48&g=1" alt="Image #1">
  <img src="https://i.stack.imgur.com/fcbpv.jpg?s=48&g=1" alt="Image #2">
  <img src="https://i.stack.imgur.com/fcbpv.jpg?s=48&g=1" alt="Image #3">
</main>


推荐阅读