如何使用 jQuery 在表格的指定索引处插入新行?

jqueryweb developmentfront end technology

要将新行插入表格的指定索引处,可以使用 jQuery 的 val() 和 insertBefore() 方法。您可以尝试运行以下代码来学习如何在表格中插入新行。 −

示例

<html>
  <head>
  <title>jQuery Example</title>
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){          
    $('#index').val($('#myTable tbody tr').length);
    $('#btn1').click(function(){
      var indx = $('#index').val()-1;
      var newRow = $('<tr><td>New row is added at index '+$('#myTable tbody tr').length+'</td></tr>');
      newRow.insertBefore($('#myTable tbody tr:nth('+indx+')'));
   });
  });
</script>
</head>
<body>
  <table id="myTable">
    <tbody>
     <tr>
      <td>This is row 1</td>
     </tr>
     <tr>
      <td>This is row 2</td>
     </tr>
    </tbody>
  </table>
  <input id="index"/>
  <button type="button" id="btn1">Add</button>
</body>
</html>

相关文章