gpt4 book ai didi

javascript - 使用包含不同可索引变量的元素来改变 DOM

转载 作者:行者123 更新时间:2023-12-01 00:06:10 25 4
gpt4 key购买 nike

希望我的标题没有误导!在我探索循环的力量的过程中,我想对此进行排序:

我需要构建这些元素:

<div id="my-id">
<div class="my-class">
<input type="checkbox" id="checkbox-1" value="a">
<label for="checkbox-1">A</label>
</div>
<div class="my-class">
<input type="checkbox" id="checkbox-2" value="b">
<label for="checkbox-2">B</label>
</div>
<div class="my-class">
<input type="checkbox" id="checkbox-3" value="c">
<label for="checkbox-3">C</label>
</div>
<!-- etc, 9 more -->
</div>

到目前为止我已经这样做了,但不知道如何继续获取元素中的字母(小写和大写)。

const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]; 

let html = "";
for (let i = 1; i <= 12; i++) {
html += `<div class = "my-class">
<input type = "checkbox" id = "checkbox-${i}" value = "?">
<label for = "checkbox-${i}">??`;
html += "</label></div>";
}
$("#here").html(html);

有没有好的方法,或者只是在 HTML 文件中硬编码会更容易? (总共 12 个输入)。

感谢您提前提供帮助!!

最佳答案

Repl Example

const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]; 

let html = "";
for (let i = 0; i < alphabet.length; i++) {
let checkboxID = 'checkbox-'.concat(String(i).toLowerCase())
let checkboxValue = alphabet[i]
html += `
<div class = "my-class">
<input type="checkbox" id="${checkboxID}" value="${checkboxValue}">
<label for="${checkboxID}">${checkboxValue}</label>
</div>`;
}

或使用Array.reduce...

const html = alphabet.reduce((_html, letter, letterIndex) => {
let checkboxID = 'checkbox-'.concat(String(letterIndex).toLowerCase())
let checkboxValue = letter
return _html += `
<div class = "my-class">
<input type="checkbox" id="${checkboxID}" value="${checkboxValue}">
<label for="${checkboxID}">${checkboxValue}</label>
</div>
`
}, '')

关于javascript - 使用包含不同可索引变量的元素来改变 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60378688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com