首页 > 解决方案 > html 复选框关联数组 - 如何在 javascript 中访问此数组?

问题描述

我正在尝试这样做:

<input type="checkbox" name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">

并像这样在javascript中访问这个数组

1.

var myarr = document.getElementsByName('appliances');
alert('here ' + myarr);

结果:警报显示“此处 [object NodeList]”

2.

var myarr = document.getElementsByName('appliances');
    alert('here ' + myarr['grill']);

结果:警报显示“此处未定义”

我怎样才能访问这个数组?

标签: javascripthtmlarrayscheckboxassociative

解决方案


Your elements all have different names as far as HTML is concerned, "appliances[microwave]", "appliances[coffee-machine]", etc. Those names are only special to certain software (for instance, PHP will handle them on a form submission).

You can find all elements whose name starts with appliances by using querySelectorAll with the selector input[name^=appliances]. Then you access the entries in that NodeList by index (0, 1, and 2):

const checkboxes = document.querySelectorAll("input[name^=appliances]");
for (let n = 0; n < checkboxes.length; ++n) {
    console.log(`${checkboxes[n].name} checked? ${checkboxes[n].checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">

If you want to access them by the names in [], you could create an object and put them on the object as properties:

function getNamedElementObject(baseName) {
    const result = {};
    // NOTE: The next line assumes there are no `]` characters in `name`
    const list = document.querySelectorAll(`[name^=${baseName}]`);
    for (const element of list) {
        const match = element.name.match(/\[([^]+)\]/);
        if (match) {
            const propName = match[1]
            result[propName] = element;
        }
    }
    return result;
}

const checkboxes = getNamedElementObject("appliances");
console.log(`checkboxes["microwave"].checked? ${checkboxes["microwave"].checked}`);
console.log(`checkboxes["coffee-machine"].checked? ${checkboxes["coffee-machine"].checked}`);
console.log(`checkboxes["grill"].checked? ${checkboxes["grill"].checked}`);
// You could also loop through by getting an array from `Object.values`:
for (const checkbox of Object.values(checkboxes)) {
    console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">

Or you could use a Map:

function getNamedElementMap(baseName) {
    const result = new Map();
    // NOTE: The next line assumes there are no `]` characters in `name`
    const list = document.querySelectorAll(`[name^=${baseName}]`);
    for (const element of list) {
        const match = element.name.match(/\[([^]+)\]/);
        if (match) {
            const propName = match[1]
            result.set(propName, element);
        }
    }
    return result;
}

const checkboxes = getNamedElementMap("appliances");
console.log(`checkboxes.get("microwave").checked? ${checkboxes.get("microwave").checked}`);
console.log(`checkboxes.get("coffee-machine").checked? ${checkboxes.get("coffee-machine").checked}`);
console.log(`checkboxes.get("grill").checked? ${checkboxes.get("grill").checked}`);
// You could also loop through via the iterator from the `values` method:
for (const checkbox of checkboxes.values()) {
    console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">


推荐阅读