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

标签 javascript html

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

我需要构建这些元素:

<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/

相关文章:

javascript - react 路由器错误: useNavigation must be used within a data router

javascript - 从项目外部导入文件

javascript - 当属性可能不存在时,与数组中的对象属性不同的值

javascript - 如何在鼠标滚轮滚动发生之前控制它?

html - 使用 bootstrap-select 出现奇怪的字形图标并且不呈现

javascript - ES6 生成器函数与 Promise

javascript - Bootstrap 表不能与 ng-repeat 一起正常工作

javascript - 如何让 Protractor 在搜索框内单击?

css - 在div中,如何使背景透明,但轮廓不透明?

html - Chrome 和 FF 之间的像素差异