首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JS for-循环中的HTML元素名称问题

JS for-循环中的HTML元素名称问题
EN

Stack Overflow用户
提问于 2022-08-18 18:25:12
回答 1查看 36关注 0票数 0

我有一些带有I、<p>id="hex-2"等的HTML元素。

我没有在脚本文件中逐个操作它们(如下所示),而是尝试使用for-循环。

代码语言:javascript
复制
/* Code I'm trying to put in For-loop */ 
document.getElementById("hex-1").innerText = data.colors[0].hex.value
document.getElementById("hex-2").innerText = data.colors[1].hex.value
document.getElementById("hex-3").innerText = data.colors[2].hex.value
document.getElementById("hex-4").innerText = data.colors[3].hex.value
document.getElementById("hex-5").innerText = data.colors[4].hex.value

我试过这样做,但不起作用;

代码语言:javascript
复制
/* Try 1 */
for(let i=0; i<data.length; i++) {
  let hexCode = `hex-${1+i}`
  
  document.getElementById(hexCode).innerText = data.colors[i].hex.value
}

/* Try 2 */
for(let i=0; i<data.length; i++) {
  let hexCode = "hex-" + (i+1)
  
  document.getElementById(hexCode).innerText = data.colors[i].hex.value
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-18 18:47:11

作为 mentioned in comments too,您似乎应该这样做:

代码语言:javascript
复制
for(let i=0; i < data.colors.length; i++) {
  let hexCode = `hex-${1+i}`
  document.getElementById(hexCode).innerText = data.colors[i].hex.value
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73407823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档