<!DOCTYPE html> <html> <head> <title>jQuery動態新增和刪除表格記錄</title> <script src="Scripts/jquery-3.4.1.min.js"></script> </head> <body> <table id="myTable"> <thead>
<tr> <th>名稱</th> <th>價格</th> </tr> </thead> <tbody> <!-- 這裡將動態新增資料 --> </tbody> </table>
<script> //$(document).ready(function () { // // 獲取表格主體 // var tbody = $("#myTable tbody"); // // 建立新的行和單元格 // var newRow = $("<tr>"); // var nameCell = $("<td>").text("蘋果"); // var priceCell = $("<td>").text("$1.99"); // // 將單元格新增到行中 // newRow.append(nameCell); // newRow.append(priceCell); // // 將行新增到表格主體中 // tbody.append(newRow); //});
$(document).ready(function () { var tbody = $("#myTable tbody"); // 資料集合 var data = [ { name: "蘋果", price: "$1.99" }, { name: "香蕉", price: "$0.99" }, { name: "橙子", price: "$2.49" } ]; // 遍歷資料集合 for (var i = 0; i < data.length; i++) { var newRow = $("<tr>"); var nameCell = $("<td>").text(data[i].name); var priceCell = $("<td>").text(data[i].price); newRow.append(nameCell); newRow.append(priceCell); tbody.append(newRow); } }); </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>jQuery動態新增和刪除表格記錄</title> <script src="Scripts/jquery-3.4.1.min.js"></script> </head> <body> <table id="myTable"> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td><input type="text" name="name"></td> <td><input type="text" name="age"></td> <td><input type="checkbox"></td> </tr> </tbody> </table> <button id="addButton">新增記錄</button> <button id="deleteButton">刪除記錄</button> <script> $(document).ready(function() { // 新增記錄按鈕點選事件 $('#addButton').click(function() { var table = $('#myTable'); var lastRow = table.find('tbody tr:last'); var newRow = lastRow.clone(); newRow.find('input').val(''); table.append(newRow); }); // 刪除記錄按鈕點選事件 $('#deleteButton').click(function() { var selectedRows = $('#myTable input[type="checkbox"]:checked'); selectedRows.each(function() { var row = $(this).closest('tr'); row.remove(); }); }); }); </script> </body> </html>