在javascript中将文本输入数据插入json数组

在javascript中将文本输入数据插入json数组,javascript,json,jsp,Javascript,Json,Jsp,伙计们,我知道这是个假问题,但我想将添加行的输入文本数据插入json数组。。每当我试图输出val时,它都会给出未定义的值。。这是我的密码 function insertRow(){ var i=1; for (var propertyNames in grid.data[0]) { var val = document.getElementsByName("input"+i).value; grid.data.push({propertyNames:val});

伙计们,我知道这是个假问题,但我想将添加行的输入文本数据插入json数组。。每当我试图输出
val
时,它都会给出未定义的值。。这是我的密码

function insertRow(){
var i=1;
  for (var propertyNames in grid.data[0]) {
      var val = document.getElementsByName("input"+i).value;
      grid.data.push({propertyNames:val});
      i++;
  }
   }

  function addRow() {
  var i = 1;
  var table = document.getElementById("table");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var cell = row.insertCell();
  var element = document.createElement("input");
  element.type = "checkbox";
  element.name = "chk";
  cell.appendChild(element);

  for (var propertyNames in grid.data[0]) {
    cell = row.insertCell(i);

    element = document.createElement("input");
    element.type = "text";
    element.size = 10;
    element.name = "input" + i;
    cell.appendChild(element);
    i++;
  }
}
我的HTML

<table>
    <tr>
    <td><input type="button" value="Add row" class="btn" id="previous" onclick="addRow();"></input>
    <input type="button" value="Insert" class="btn" id="insert" onclick="insertRow();"></input>
    </td>
    </tr>
</table>

很多错误

  • var table=document.getElementById(“表”)。您没有
    id=table的元素

  • 网格中。数据[0]
    网格为
    null

  • 开发者控制台
    在任何浏览器中-它都是非常有用的工具


  • 是的。。请仔细看看您的html代码中没有name属性。请查看我的答案以了解更多详细信息