在显示其同时还会打印本地存储中的旧数据

时间:2019-01-28 11:20:06

标签: javascript arrays json local-storage input-field

  function addrow() {
            debugger;
            var person = [];
            if (localStorage.person1 != null && localStorage.person1 !=undefined) {
                var person = JSON.parse(localStorage.person1);


            }

            var name = document.getElementById('name').value;
            var city = document.getElementById('city').value;
            person.push({ 
                pname: name,
                pcity: city
            });


            localStorage.setItem('person1', JSON.stringify(person));
            bind();
        }

    function bind() {
        debugger;
        var per_list = JSON.parse(localStorage.getItem('person1'));
        for (i = 0; i < per_list.length; i++ ) {
                var table = document.getElementById('ptable');
                var row = table.insertRow(0);
                var col1 = row.insertCell(0);
                var col2 = row.insertCell(1);
            col1.innerHTML = per_list[i].pname;
            col2.innerHTML = per_list[i].pcity;
            }

        }

我有两个字段namecity;现在,单击“添加行”,在第一个ok上打印value,但随后又打印两个{{1 }}和old的值。而且,我只想在new输入下添加新条目。.预先感谢

1 个答案:

答案 0 :(得分:0)

由于要显示.bind函数中的所有元素,因此需要清除表。

function bind() {
  debugger;
  var per_list = JSON.parse(localStorage.getItem('person1'));
  // clear the table
  var table = document.getElementById('ptable');
  for (var i = 0, rows = table.rows.length; i < rows; i++) {
    table.deleteRow(0)
  }
  // fill the table
  for (i = 0; i < per_list.length; i++) {
    var row = table.insertRow(0);
    var col1 = row.insertCell(0);
    var col2 = row.insertCell(1);
    col1.innerHTML = per_list[i].pname;
    col2.innerHTML = per_list[i].pcity;
  }
}