jQuery 添加新的表行不在表的末尾

jQuery Adding New Table Row Not at the End of the Table

本文关键字:添加 jQuery      更新时间:2023-09-26

我有一个HTML表格,并希望允许用户单击按钮来添加新行,但新行不会添加到表的末尾,而是添加到输入字段的最后一行之后。

我已经在以下位置设置了一个示例 JSFiddle:

http://jsfiddle.net/n7Gup/2/

我有一个"新建行"按钮,

但它没有克隆最后一行输入(即"新建行"按钮所在的行)。我需要修改它,以便它将在这些输入行的最后一行之后插入一个新行。

这是我从在线教程中找到的脚本:

$(document).ready(function($)
{
  // trigger event when button is clicked
  $("#button2").click(function()
  {
    // add new row to table using addTableRow function
    addTableRow($("#nextYear"));
    // prevent button redirecting to new page
    return false;
  });
  // function to add a new row to a table by cloning the last row and
  // incrementing the name and id values by 1 to make them unique
  function addTableRow(table)
  {
    // clone the last row in the table
    var $tr = $(table).find("tbody tr:last").clone();
    // get the name attribute for the input and select fields
    $tr.find("input,select").attr("name", function()
    {
      // break the field name and it's number into two parts
      var parts = this.id.match(/('D+)('d+)$/);
      // create a unique name for the new field by incrementing
      // the number for the previous field by 1
      return parts[1] + ++parts[2];
    // repeat for id attributes
    }).attr("id", function()
    {
      var parts = this.id.match(/('D+)('d+)$/);
      return parts[1] + ++parts[2];
    });
    // append the new row to the table
    $(table).find("tbody tr:last").after($tr);
  };
});

创建的新行可以将所有输入字段都留空,因为用户将重新开始。还有没有办法让"新建行"按钮只出现一次,并且始终在活动输入的最后一行。例如,最初只有一行,但如果单击"新建行"按钮,则会在初始行下方创建第二行,并且"新建行"按钮现在仅出现在此新创建的行上。

感谢任何帮助 - 我是Javascript的新手。

这是一个解决方案

http://jsfiddle.net/7vuZf/3/

基本上,您只需将引用传递给单击的按钮并从那里计算出您在表中的位置 - 保存对当前最后一行的引用(使用 closest(),克隆它(带有事件),删除原始中的新行按钮(您可能需要用删除按钮替换它),然后在原始之后插入克隆。

此外,现在您可能不需要对传递给单击处理程序的表对象的引用(不过我将其保留在代码中)。