javascript - 循环只返回一个元素
问题描述
我需要遍历图像以获取所有图像的 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())
解决方案
您需要使用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>
推荐阅读
- python-3.x - 无需安装即可获取包版本和依赖项
- terraform - Terraform 从子模块输出定义 FortiOS VIP 组成员块
- datatables - Jquery Inline 编辑器插件在下拉选择中保存数字
- vuejs3 - Vue 3 - 反应性功能解决方法?
- node.js - Gulp 3.9.1 导致语法错误
- ssl - SSL 握手显示密码 0000
- ios - 在 Firebase 中播放和存储视频
- firebase - Swift 包的 Firebase productItem 名称
- python - 限制由 Google Cloud Bigtable 中的前缀定义的行集
- r - 按组组合、合并、合并行并将某个值替换为另一个值而不进行旋转