2016-11-17 246 views
0

我得到了一個錯誤,我不知道如何解決它,請幫助:) 代碼:的Javascript遺漏的類型錯誤:checkbox.setAttributeNode不是一個函數

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;"> 

你能幫助我嗎?

回答

2

getElementsByName回報集合,所以你需要使用checkbox[0].setAttributeNode(att);。我還建議你在設置屬性前檢查元素的存在。

+0

thx它的工作! –

3

getElementsByName()返回文檔中給定名稱的節點列表集合。所以,你應該訪問第一要素,通過做

checkbox[0].setAttributeNode(att); 
+0

thx它的工作! –

3

document.getElementsByName(value);返回節點列表而不是單個節點。您應該遍歷列表並在列表中的每個節點上使用setAttributeNode()

相關問題