You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码在表格首行后插入新行?当前插入位置为底部

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:

  1. Locate the current row: First, we need to grab the <tr> element that holds the "Add" button you clicked. We can do this using closest('tr') on the button element.
  2. Replace append() with after(): Instead of adding the new row to the end of the tbody, we'll insert it right after the current row.
  3. Fix duplicate IDs (bonus!): Your current code uses the same id="middleInitial" and id="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 addButton for reusability.
  • Used addButton.closest('tr') to get the parent row of the clicked button.
  • Replaced $('#addRow').append(content) with addButton.closest('tr').after(content) to insert the new row immediately after the current one.
  • Updated the id attributes 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:06:06