HTML 怎么只给勾中的checkbox元素添加input,而没有勾中的checkbox元素不添加input
时间: 2023-06-25 20:03:21 浏览: 51
可以通过 JavaScript 来实现这个功能。首先,给每个 checkbox 添加一个监听事件,当勾选时,添加 input 元素,取消勾选时,移除 input 元素。例如:
```html
<label><input type="checkbox" id="checkbox1"> Checkbox 1</label>
<label><input type="checkbox" id="checkbox2"> Checkbox 2</label>
<script>
const checkbox1 = document.getElementById("checkbox1");
const checkbox2 = document.getElementById("checkbox2");
checkbox1.addEventListener("change", function() {
if (this.checked) {
const input = document.createElement("input");
input.type = "text";
input.name = "checkbox1_input";
this.parentNode.appendChild(input);
} else {
const input = this.parentNode.querySelector("input[type=text]");
if (input) {
this.parentNode.removeChild(input);
}
}
});
checkbox2.addEventListener("change", function() {
if (this.checked) {
const input = document.createElement("input");
input.type = "text";
input.name = "checkbox2_input";
this.parentNode.appendChild(input);
} else {
const input = this.parentNode.querySelector("input[type=text]");
if (input) {
this.parentNode.removeChild(input);
}
}
});
</script>
```
上面的代码创建了两个 checkbox 元素,分别对应 id 为 checkbox1 和 checkbox2。当勾选 checkbox1 时,会添加一个 name 为 checkbox1_input 的 input 元素;当勾选 checkbox2 时,会添加一个 name 为 checkbox2_input 的 input 元素。如果取消勾选,则会移除相应的 input 元素。