Javascript Uncaught TypeError: checkbox.setAttributeNode is not a function

Javascript Uncaught TypeError: checkbox.setAttributeNode is not a function

我遇到了一个错误,我不知道如何解决,请帮忙:) 代码:

var ls_contextid1=JSON.parse(localStorage.getItem('completedArray')) || [];
      for (var i = 0; i < ls_contextid1.length; i++){
        var obj = ls_contextid1[i];
        for (var key in obj){
          var value = obj[key];
          var checkbox=document.getElementsByName(value);
          doc[i] =value;

          var att = document.createAttribute('checked');      
          att.value = 'checked';   

        checkbox.setAttributeNode(att);

        }
      }

}

这是错误信息:

Uncaught TypeError: checkbox.setAttributeNode is not a function

本地存储包含 json:

[{"contextid":"470"},{"contextid":"468"},{"contextid":"467"},{"contextid":"463"},{"contextid":"463"},{"contextid":"464"}]

和 HTML 代码:

<input name="470" type="checkbox" disabled="disabled" style="margin-left:50px;">

你能帮帮我吗?

getElementsByName() returns 文档中具有给定名称的节点列表集合。所以你应该通过

访问第一个元素
checkbox[0].setAttributeNode(att);

getElementsByNamereturns合集,所以需要用到checkbox[0].setAttributeNode(att);。我还建议您在设置属性之前检查元素是否存在。

document.getElementsByName(value); returns 一个节点 list 而不仅仅是一个节点。您应该遍历列表并在列表中的每个节点上使用 setAttributeNode()