删除行时如何更新动态表的行索引?

时间:2016-04-23 06:01:15

标签: javascript jquery html

我通过单击“添加”按钮动态创建表行。我想在创建的行中添加序列号,工作正常。但是当删除行时,我希望现有的行号得到更新,而不是 工作。

请忽略Name列中的undefined ..这是一些小问题而不是关注.. Jquery解决方案也没关系。

以下是代码..

function addRow() {
  var myName = document.getElementById("name");
  var table = document.getElementById("myTableData");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  row.insertCell(0).innerHTML = '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
  row.insertCell(1).innerHTML = name.value;
  row.insertCell(2).innerHTML = row.rowIndex;
}

function deleteRow(obj) {
  var index = obj.parentNode.parentNode.rowIndex;
  var table = document.getElementById("myTableData");
  table.deleteRow(index);
}

function addTable() {
  var myTableDiv = document.getElementById("myDynamicTable");
  var table = document.createElement('TABLE');
  table.border = '1';
  var tableBody = document.createElement('TBODY');
  table.appendChild(tableBody);
  for (var i = 0; i < 3; i++) {
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);
    for (var j = 0; j < 4; j++) {
      var td = document.createElement('TD');
      td.width = '75';
      td.appendChild(document.createTextNode("Cell " + i + "," + j));
      tr.appendChild(td);
    }
  }
  myTableDiv.appendChild(table);
}

function load() {
  console.log("Page load finished");
}
<!DOCTYPE html>
<html>

<head>
  <title>HTML dynamic table using JavaScript</title>
  <script type="text/javascript" src="app.js"></script>
</head>

<body onload="load()">
  <div id="myform"> <b>Simple form with name and age ...</b> 
    <table>
      <tr>
        <td>Name:</td>
        <td>
          <input type="text" id="name">
        </td>
      </tr>
      <tr>
        <td>
          <input type="button" id="add" value="Add" onclick="Javascript:addRow()">
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
    </table>
  </div>
  <div id="mydata"> <b>Current data in the system ...</b> 
    <table id="myTableData" border="1" cellpadding="2">
      <tr>
        <td>&nbsp;</td>
        <td><b>Name</b>
        </td>
        <td><b>Sr no</b>
        </td>
      </tr>
    </table>&nbsp;
    <br/>
  </div>
  <div id="myDynamicTable"></div>
</body>

</html>

0 个答案:

没有答案