如何用jQuery实现表格行号动态添加及行删除功能?
Hey there! Let's tackle your two requirements step by step—adding dynamic row numbers and implementing that X-style delete button, plus making sure row numbers stay in order after deletion. Here's the full working solution tailored to your existing code:
Updated HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="text" id="name" placeholder="Name"> <input type="button" class="add-row" value="Add Row"> </form> <table> <thead> <tr> <th>#</th> <th>Name</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Peter Parker</td> <td><button class="delete-btn">X</button></td> </tr> </tbody> </table>
Modified jQuery Code
$(document).ready(function(){ // Helper function to refresh row numbers function updateRowNumbers() { $("table tbody tr").each(function(index) { // Set first td to index + 1 (since JS indexes start at 0) $(this).find("td:first").text(index + 1); }); } // Add new row when "Add" is clicked $(".add-row").click(function(){ var name = $("#name").val(); // Optional: Prevent empty rows from being added if(name.trim() !== "") { var markup = `<tr> <td></td> <td>${name}</td> <td><button class="delete-btn">X</button></td> </tr>`; $("table tbody").append(markup); updateRowNumbers(); // Update numbers after adding $("#name").val(""); // Clear input for next entry } }); // Delete row when X button is clicked (uses event delegation for dynamic rows) $("table tbody").on("click", ".delete-btn", function(){ $(this).closest("tr").remove(); updateRowNumbers(); // Reorder numbers after deletion }); // Initialize row numbers on page load updateRowNumbers(); });
Quick Breakdown of Key Changes:
- Dynamic Row Numbers: The
updateRowNumbers()function loops through all table rows and resets the first column to a sequential number. We call this every time a row is added or deleted to keep numbers in sync. - X Delete Button: Each row now includes a button with class
delete-btn. We use event delegation (on("click", ".delete-btn", ...)) to make sure even dynamically added buttons work—since these buttons don't exist when the page first loads, we attach the click event to the parenttbodyinstead. - Polished UI Touches: Added a check to block empty rows and clear the input field after adding a row, which makes the interface more intuitive.
- Table Header Update: Added columns for row numbers (
#) and actions to match your desired layout.
If you want the X button to match the style in your reference, add this simple CSS:
.delete-btn { background: none; border: none; color: #dc3545; cursor: pointer; font-weight: bold; font-size: 1.1em; }
内容的提问来源于stack exchange,提问作者Valentin Georgiev
相关产品推荐
相关产品推荐

