简体   繁体   English

JavaScript INDEX_SIZE_ERR:DOM异常1

[英]JavaScript INDEX_SIZE_ERR: DOM Exception 1

In the following code, I am receiving the said error, and am not exactly sure why. 在下面的代码中,我收到了上述错误,并不完全确定原因。 I have looked at other threads on here, but cannot seem to find the fault. 我在这里看过其他线程,但似乎无法找到错误。

The purpose of the script is to save arrays of strings into localstorage. 该脚本的目的是将字符串数组保存到localstorage中。 These string arrays are then loaded into a table. 然后将这些字符串数组加载到表中。

The following function gets the values from my web form fields:- 以下函数从我的Web表单字段中获取值: -

function saveContact() {
        var contact = [nameDOM.value, addDOM.value, townDOM.value, postalDOM.value, mobDOM.value];
        localStorage.setItem(window.localStorage.length, contact);
        showContacts();
  }

This function places this information into a table:- 此函数将此信息放入表中: -

 function showContacts() {
        for(i=0; i<window.localStorage.length; i++) {
          var contactRow = cTableDOM.insertRow(i);
          var contactCell = contactRow.insertCell(i);
          var text = document.createTextNode(localStorage.getItem(i));
          contactCell.appendChild(text);
        }
  }

The behavior I am receiving is this; 我收到的行为是这样的; when I try to enter different "contacts" into my table, the first "contact" is repeated instead of the latter "contacts". 当我尝试将不同的“联系人”输入我的表格时,重复第一个“联系人”而不是后者的“联系人”。

The problem is that you are creating a new row and calling insertCell(2) . 问题是您正在创建一个新行并调用insertCell(2) Because this is greater than the number you get the INDEX_SIZE_ERR. 因为这大于您获得INDEX_SIZE_ERR的数字。

From Mozilla (emphasis added): 来自Mozilla (重点补充):

If index is -1 or equal to the number of cell, the cell is appended as the last cell in the row. 如果index为-1或等于单元格数,则将单元格作为行中的最后一个单元格附加。 If index is omitted or greater than the number of rows, an error will result. 如果省略index或大于行数,将导致错误。

You can also just call appendChild on a newly created td . 您也可以在新创建的td上调用appendChild

var contactCell = contactRow.appendChild(document.createElement("td"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM