gpt4 book ai didi

JavaScript:无法动态重置动态创建的复选框的复选框值

转载 作者:行者123 更新时间:2023-12-03 00:32:25 26 4
gpt4 key购买 nike

我用纯 JavaScript 动态创建了一组复选框和标签。这工作正常并且显示复选框:

const label = document.createElement("label");
const checkbox = document.createElement("input");
const description = document.createTextNode(course[i].name);

checkbox.type = "checkbox";
checkbox.id = "checkbox-" + course[i].name;
checkbox.value = course[i].name;

label.appendChild(checkbox);
label.appendChild(description);

const mainDiv = document.getElementById("main");
mainDiv.appendChild(label);

但是,当我单击屏幕上其他位置的按钮时,我需要该 eventHandler 重置所有复选框值,以便它们全部处于未选中状态。我尝试了以下两个选项。没有一个给我浏览器错误,但都没有达到预期的效果:

for (let i = 0, l = allItems.length; i < l; ++i) {
document.getElementById("checkbox-" + allItems[i].name).checked = false;
}

$("input[type=checkbox]").each(function () {
this.checked = false;
});

在浏览器控制台内,我可以检索“checked”的值,并将其设置为 false,但 UI 不会反射(reflect)此更改。我在 StackOverflow 上查遍了。尽管有人提出类似的问题,但我无法获得适合我的建议解决方案。

Browser debugging results

最佳答案

您必须取消选中按钮事件处理函数内的复选框:

$('#reset').click(function(){
$("input[type=checkbox]").each(function () {
this.checked = false;
});
});

演示:

var course = [{name: 'TestCourse1'},{name: 'TestCourse2'},{name: 'TestCourse3'}]
for(var i = 0; i < course.length; i++){
const label = document.createElement("label");
const checkbox = document.createElement("input");
const description = document.createTextNode(course[i].name);

checkbox.type = "checkbox";
checkbox.id = "checkbox-" + course[i].name;
checkbox.value = course[i].name;

label.appendChild(checkbox);
label.appendChild(description);

const mainDiv = document.getElementById("main");
mainDiv.appendChild(label);
}

$('#reset').click(function(){
$("input[type=checkbox]").each(function () {
this.checked = false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main"></div>

<button id="reset">Reset</button>

关于JavaScript:无法动态重置动态创建的复选框的复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com