首页 > 解决方案 > 将复选框的值作为空对象获取

问题描述

我正在尝试将选中复选框的值作为空对象(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({})?如果这不可能,我应该重写代码吗?

标签: javascript

解决方案


数组包含值,但对象包含属性,它有一个值,也有一个名称。所以如果你想使用一个对象而不是一个数组,你还需要使用复选框的名称。例如:

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.


推荐阅读