如何修改代码在表格首行后插入新行?当前插入位置为底部
How to Insert New Row Right After the Clicked Row Instead of Table Bottom
Got it, let's get this sorted! The issue right now is that you're using append() which adds content to the end of the <tbody> element. To insert the new row immediately after the row containing the clicked "Add" button, we need to target that specific row and use jQuery's after() method instead.
Step-by-Step Fix:
- Locate the current row: First, we need to grab the
<tr>element that holds the "Add" button you clicked. We can do this usingclosest('tr')on the button element. - Replace
append()withafter(): Instead of adding the new row to the end of the tbody, we'll insert it right after the current row. - Fix duplicate IDs (bonus!): Your current code uses the same
id="middleInitial"andid="lastName"for every new row—IDs must be unique in HTML, so we'll update those to match the naming pattern of the firstName input.
Modified JavaScript Code:
function addRow(index) { const addButton = $('#addButton' + index); addButton.attr("disabled", true); const counter = ++index; // Fixed duplicate IDs here const content = `<tr> <td align="right">First Name:</td> <td align="left"><input id="personArray_${counter}__firstName" name="personArray[${counter}].firstName" type="text" value=""></td> <td align="right">Middle Initial:</td> <td align="left"><input id="personArray_${counter}__middleInitial" name="personArray[${counter}].middleInitial" type="text" value=""></td> <td align="right">Last Name:</td> <td align="left"><input id="personArray_${counter}__lastName" name="personArray[${counter}].lastName" type="text" value=""></td> <td><input type="button" class="btn btn-xs valid" id="addButton${counter}" onclick="addRow('${counter}')" value="Add" aria-invalid="false"></td> </tr>`; // Find the current row and insert the new row right after it addButton.closest('tr').after(content); };
What Changed:
- We store the clicked button in
addButtonfor reusability. - Used
addButton.closest('tr')to get the parent row of the clicked button. - Replaced
$('#addRow').append(content)withaddButton.closest('tr').after(content)to insert the new row immediately after the current one. - Updated the
idattributes for middleInitial and lastName inputs to be unique (matching the firstName pattern) to avoid HTML validation issues.
Now when you click "Add" on any row, the new row will pop up right below it instead of at the bottom of the table!
内容的提问来源于stack exchange,提问作者user8401416
相关产品推荐
相关产品推荐

