javascript - 将复选框的值作为空对象获取
问题描述
我正在尝试将选中复选框的值作为空对象(checked = {})
这是我的代码:
for (const l of i.options){
const x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("class", "checkboxClass");
x.value = l;
const y = document.createElement("LABEL");
const t = document.createTextNode(l);
y.appendChild(t);
const div = document.createElement("div");
div.style.height = "5px";
div.appendChild(x);
div.appendChild(y);
document.getElementById("checkbox").appendChild(div);
window.data.appendChild(x);
window.data.appendChild(y);
window.data.appendChild(div);
}
const checked = [];
document.querySelectorAll("input:checked").forEach((item) => {
checked.push(item.value);
});
我怎样才能将它从一个更改empty array ([])
为一个empty object({})
?如果这不可能,我应该重写代码吗?
解决方案
数组包含值,但对象包含属性,它有一个值,也有一个名称。所以如果你想使用一个对象而不是一个数组,你还需要使用复选框的名称。例如:
const checked = {};
document.querySelectorAll("input:checked").forEach((item) => {
checked[item.name] = item.value;
});
但是,要使其正常工作,您需要为复选框提供名称,而它们目前似乎没有。我的意思是,您可以使用复选框的索引作为属性名称:
const checked = {};
document.querySelectorAll("input:checked").forEach((item, index) => {
checked[index] = item.value;
});
...但是此时您基本上是在创建一个数组,只是length
没有Array.prototype
.
推荐阅读
- spring - 将 Spring App 部署到 Heroku 时失败
- r - R 中的 PostgreSQL SSH 隧道连接(尝试连接时 ssh_tunnel 崩溃)
- reactjs - Material-UI + 全局主题链接
- android - 无法实例化接收器 GPBroadcastReceiver:在路径上找不到类“com.packagename.GPBroadcastReceiver”:DexPathList
- android - 微软 Azure 登录
- macos - 在某些类型的软件中执行命令行的问题,但在其他类型的软件中却没有
- r - 如何计算使用 nnet 包创建的多项 logit 模型的边际效应?
- c# - aspx c#中的问题在上传之前重命名文件并保存到数据库中的名称
- powershell - Powershell 提升并传递命令
- recursion - 类似 glob() 的 C 函数,但支持“**”递归语法?