求助:如何通过循环遍历图片标题数组生成HTML代码
问题修正方案
你的代码存在几个关键错误,以下是修正要点和完整代码:
错误点说明
- 循环内部不能直接写HTML标签,必须把HTML内容以字符串形式拼接到
htmlCode变量中 - 图片路径
slidei.jpg需要替换为对应计数器的文件名,要通过模板字符串把i的值插入进去,写成slide${i}.jpg - figcaption的内容需要正确嵌入
captions[i]的值,同样要通过字符串拼接实现 document.getElementById的参数必须是字符串,所以要给gallery加上单引号或双引号
修正后的完整代码
let captions = new Array(14); captions[0] = "International Space Station fourth expansion [2009]"; captions[1] = "Assembling the International Space Station [1998]"; captions[2] = "The Atlantis docks with the ISS [2001]"; captions[3] = "The Atlantis approaches the ISS [2000]"; captions[4] = "The Atlantis approaches the ISS [2000]"; captions[5] = "International Space Station over Earth [2002]"; captions[6] = "The International Space Station first expansion [2002]"; captions[7] = "Hurricane Ivan from the ISS [2008]"; captions[8] = "The Soyuz spacecraft approaches the ISS [2005]"; captions[9] = "The International Space Station from above [2006]"; captions[10] = "Maneuvering in space with the Canadarm2 [2006]"; captions[11] = "The International Space Station second expansion [2006]"; captions[12] = "The International Space Station third expansion [2007]"; captions[13] = "The ISS over the Ionian Sea [2007]"; let htmlCode = ""; for (let i = 0; i < captions.length; i++) { htmlCode += ` <figure> <img alt='' src='slide${i}.jpg' /> <figcaption>${captions[i]}</figcaption> </figure> `; } document.getElementById('gallery').innerHTML = htmlCode;
兼容写法(不支持ES6时使用)
如果运行环境不支持ES6模板字符串,可改用传统字符串拼接方式:
for (let i = 0; i < captions.length; i++) { htmlCode += "<figure>" + "<img alt='' src='slide" + i + ".jpg' />" + "<figcaption>" + captions[i] + "</figcaption>" + "</figure>"; }
内容的提问来源于stack exchange,提问作者Austin Rivera-Bennett
相关产品推荐
相关产品推荐

