javascript - 如何在 For 循环中从 Web 打印图像
问题描述
所以我试图通过 For Loop 自动打印很多图像。我有三个列表分别包含某种类型的图像:森林、人物和海洋。我想浏览并打印每个类别中的每张图片。我已经尝试了几个小时,但我是一个完整的初学者,所以我可能错过了一些愚蠢的事情。到目前为止,这是我的代码:
<script>
const forrest = ["https://cdn.pixabay.com/photo/2020/03/20/13/23/mountain-4950653_1280.jpg", "https://cdn.pixabay.com/photo/2020/01/07/14/18/forrest-4747692_1280.jpg", "https://cdn.pixabay.com/photo/2018/07/30/11/30/landscape-3572374_1280.jpg"]
const people = ["https://cdn.pixabay.com/photo/2014/09/07/21/52/city-438393_1280.jpg", "https://cdn.pixabay.com/photo/2015/05/15/14/50/concert-768722_1280.jpg", "https://cdn.pixabay.com/photo/2017/08/06/12/06/people-2591874__480.jpg"]
const ocean = ["https://cdn.pixabay.com/photo/2016/11/29/04/19/ocean-1867285_1280.jpg", "https://cdn.pixabay.com/photo/2018/06/13/18/20/wave-3473335__340.jpg", "https://cdn.pixabay.com/photo/2016/12/17/14/33/wave-1913559__340.jpg"]
const type = [forrest, people, ocean]
function myFunction() {
for (var i = 0; i < type.length; i++); {
var list = type[i];
for (var pictures = 0; pictures <= list.length; pictures++); {
var img = document.createElement("img");
img.src = list[pictures];
document.body.appendChild(img);
}
}
}
</script>
我在上面的代码中插入了一些示例照片。我的照片也来自网络。该代码打印第一个列表中的第一张照片,但不打印任何其他照片。
解决方案
你的 for 循环是错误的。for (var i = 0; i > type.length; i++)
意味着只要 i 大于 type.length,for 循环就会继续。第一次迭代是:0 > 3
所以它不会工作。您需要检查 i 是否小于 type.length。喜欢 :for (var i = 0; i < type.length; i++)
在这里查看更多信息:MDN For LOOP
推荐阅读
- git - 我在 openwrt 路由器上创建了一个 git 存储库,但在我的 mac 上出现错误
- javascript - 如何从父组件调用子组件功能?
- python - 如何不断更新变量(使用带有 tkinter 的旋转框)?
- kotlin - Kotlin groupby 值作为集合而不是列表
- r - R 中的 Web 抓取(使用 rvest) - 循环多年
- android - 将 JSON 数据从手持应用程序发送到可穿戴设备
- angular - 为什么我需要调用detectChanges / whenStable 两次?
- json - 需要詹姆斯路径输出
- android - 突然 FirebaseMessagingService 无法正常工作
- python - SQL 查询中 OptionMenu 中的选项重复