如何动态地向复选框添加标签



我希望我的复选框看起来像这样:

<input type="checkbox"name="id">Check 1</input>
<input type="checkbox"name="id">Check 2</input>
<input type="checkbox"name="id">Check 3</input>

如何添加一些标签?

我的代码:

response.forEach(row => {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name =  model.toLowerCase()+"_id";
checkbox.value = row.id;
control.appendChild( checkbox);
});

html中的标签是一个单独的 HTML 元素:

<label for="my_checkbox_1">Checkbox 1</label>
<input type="checkbox" id="my_checkbox_1"/>
<br>
<label for="my_checkbox_2">Checkbox 2</label>
<input type="checkbox" id="my_checkbox_2"/>
<br>
<label for="my_checkbox_3">Checkbox 3</label>
<input type="checkbox" id="my_checkbox_3"/>

尝试向函数添加类似以下内容:

var label = document.createElement('label');
label.htmlFor = "ID_OF_CHECKBOX_HERE";
label.innerHTML = "LABEL_TEXT_HERE";

<input />标签是自闭合的。要向复选框添加标签,您需要将其包装在该标签中:

<label><input type="checkbox" name="id"> Check 3</label>

这是一个演示:

var response = [{id: 1, name: "Check 1"}, {id: 2, name: "Check 2"}, {id: 2, name: "Check 3"}];
var model = "foo";
response.forEach(row => {
// Create a label
var label = document.createElement('label');
// Create a checkbox
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = model.toLowerCase() + "_id";
checkbox.value = row.id;
// Append the checkbox to the label
label.appendChild(checkbox);
// Append the label text to the label
label.appendChild( document.createTextNode(row.name) );
// Append the label to the control area
control.appendChild(label);
});
label { display: block; }
<div id="control"></div>

有几种方法可以做你想做的事

  • DOM API
  • 模板文本
  • <template>

请看下面的例子

使用模板文本

const response = [
{
id: 1,
},
{
id: 2,
},
{
id: 3,
},
{
id: 4,
},
];
const inputs = response
.map(
({ id }) => `<label>
<input type="checkbox" name="${id}" />
Check ${id}
</label>`
)
.join("");
document.querySelector("#root").innerHTML = inputs;
<div id="root"></div>

使用<template>

const response = [
{
id: 1,
},
{
id: 2,
},
{
id: 3,
},
{
id: 4,
},
];
const root = document.querySelector("div#root");
const template = document.querySelector("#input-template");
response.forEach(({ id }) => {
const clone = template.content.cloneNode(true);
clone.querySelector('input[type="checkbox"]').setAttribute("name", id);
clone.querySelector("span").textContent = `Check ${id}`;
root.appendChild(clone);
});
<div id="root"></div>
<template id="input-template">
<label> <input type="checkbox" name="" id="" /> <span></span> </label>
</template>

DOM API 的问题在于它很快就会变得非常冗长和重复,并且这些总和使其难以维护。

最新更新