jQuery动态添加和删除表格记录
<!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>