我有一些带有I、<p>、id="hex-2"等的HTML元素。
我没有在脚本文件中逐个操作它们(如下所示),而是尝试使用for-循环。
/* 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我试过这样做,但不起作用;
/* 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
}发布于 2022-08-18 18:47:11
作为 mentioned in comments too,您似乎应该这样做:
for(let i=0; i < data.colors.length; i++) {
let hexCode = `hex-${1+i}`
document.getElementById(hexCode).innerText = data.colors[i].hex.value
}https://stackoverflow.com/questions/73407823
复制相似问题