通过直接 html 代码:
<div> <input type="checkbox" name="color" id="red"> <label for="red">Red</label> </div> <div> <input type="checkbox" name="color" id="green"> <label for="green">Green</label> </div> <div> <input type="checkbox" name="color" id="Blue"> <label for="Blue">Blue</label> </div> <div> <input type="checkbox" name="color" id="yellow"> <label for="yellow">Yellow</label> </div>
通过JS代码,创建每个元素、属性、内容并将子级appendChild到父级:
<body> <div id="root"></div> <script> const root = document.getElementById("root"); const colors = ["Red", "Green", "Blue", "Yellow"]; colors.forEach((color) => { // create id const id = color; // create label const label = document.createElement("label"); label.setAttribute("for", id); // create checkbox input element const input = document.createElement("input"); input.type = "checkbox"; input.name = "color"; input.id = id; input.value = color; // appendChild child to parent label.appendChild(input); label.appendChild(document.createTextNode(color)); root.appendChild(label); }); </script> </body>
通过 JS 代码,带有innerHTML 和模板文字:
<body> <div id="root"></div> <script> const root = document.getElementById("root"); const colors = ["Red", "Green", "Blue", "Yellow"]; const checkbox = colors.map((color)=>`<label for="${color}"> <input type="checkbox" name="color" id="${color}" value="${color}" > ${color}</label> ` ).join(""); root.innerHTML = checkbox; </script> </body>
以上是创建复选框的一些有效方法的详细内容。更多信息请关注PHP中文网其他相关文章!