如何使用 JavaScript 将行中某些单元格的内容编辑到表格中?

我使用 JavaScript 来更改使用 JS 创建的表中某些单元格的内容,使用下面的行:

document.getElementById("tableID").rows[x].cells[y].innerHTML = "someValue";


但总是收到错误消息:(Uncaught TypeError:无法读取未定义的属性“单元格”),那么出了什么问题?


btnSave.onclick = function() {

  var table    = document.getElementById("table");

  var row      = table.insertRow(document.getElementById("table").rows.length);

  var cellID   = row.insertCell(0);

  var cellNAME = row.insertCell(1);

  var cellAGE  = row.insertCell(2);

  cellID.innerHTML   = " some id ";

  cellNAME.innerHTML = " some name ";

  cellAGE.innerHTML  = " some age ";

}


edit.onclick = function() {

  var x;

  for (x = 1; x <= document.getElementById("table").rows.length; x++) {      

    document.getElementById("table").rows[x].cells[0].innerHTML = x;

  }

}

<button id="btnSave">Save</button>

<button id="edit">edit</button>

<table id="table">

    <tr>

        <th>ID</th>

        <th>Name</th>

        <th>Age</th>

    </tr>

</table>


RISEBY
浏览 98回答 1
1回答

翻阅古今

for 循环中应该从 x = 0 开始。这是一个可行的解决方案:btnSave.onclick = function() {var table = document.getElementById("table");var row = table.insertRow(document.getElementById("table").rows.length);var cellID = row.insertCell(0);var cellNAME = row.insertCell(1);var cellAGE = row.insertCell(2);cellID.innerHTML = " some id ";cellNAME.innerHTML = " some name ";cellAGE.innerHTML = " some age ";}edit.onclick = function() {&nbsp;var x;&nbsp; &nbsp; for (x = 0; x < document.getElementById("table").rows.length; x++) {&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("table").rows[x].cells[0].innerHTML = x;&nbsp; &nbsp; }}<button id="btnSave">Save</button><button id="edit">edit</button><table id="table">&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <th>ID</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Name</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Age</th>&nbsp; &nbsp; </tr></table>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript