如何使用 jQuery 在表格中新增新行?


使用事件委託在網頁上使用 jQuery 新增新行和刪除表單行的功能。

首先,在 HTML 中設定一個按鈕以新增新行

<button id="newbtn">
   Add new Row
</button>

現在在按鈕點選事件中,設定程式碼

$("#newbtn").click(function () {
}

示例

 活動演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      var x = 1;
      $("#newbtn").click(function () {
         $("table tr:first").clone().find("input").each(function () {
            $(this).val('').attr({
               'id': function (_, id) {
                  return id + x
               },
               'name': function (_, name) {
                  return name + x
               },
               'value': ''
            });
         }).end().appendTo("table");
         x++;
      });

      $(document).on('click', 'button.deletebtn', function () {
         $(this).closest('tr').remove();
         return false;
      });
   });
</script>
</head>
<body>
<table>
<tr>
<td>
<button type="button" class="deletebtn" title="Remove row">X</button>
</td>
<td>
<input type="text" id="txtTitle" name="txtTitle">
</td>
<td>
<input type="text" id="txtLink" name="txtLink">
</td>
</tr>
</table>
<button id="newbtn">Add new Row</button>
</body>
</html>

更新於:2020 年 6 月 20 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告