简体   繁体   中英

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. These string arrays are then loaded into a table.

The following function gets the values from my web form fields:-

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) . Because this is greater than the number you get the INDEX_SIZE_ERR.

From Mozilla (emphasis added):

If index is -1 or equal to the number of cell, the cell is appended as the last cell in the row. If index is omitted or greater than the number of rows, an error will result.

You can also just call appendChild on a newly created td .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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