希望我的标题没有误导!在探索循环的强大功能的过程中,我想对以下内容进行排序:
我需要构建这些元素:
<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个输入)。
提前感谢您的帮助!!
发布于 2020-02-24 23:12:42
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>
`
}, '')发布于 2020-02-24 23:12:30
您可以遍历字母表数组,并使用alphabeti来访问所需的字母。然后你可以把它放在value属性和你的标签中。
如果需要小写版本,请使用.toLowerCase()
for (let i = 0; i < alphabet.length; i++) {
html += `<div class = "my-class">
<input type = "checkbox" id = "checkbox-${i}" value = "${alphabet[i].toLowerCase()}">
<label for = "checkbox-${i}">${alphabet[i]}</label></div>`;
}https://stackoverflow.com/questions/60378688
复制相似问题