【问题标题】:jQuery Adding New Table Row Not at the End of the TablejQuery添加新表格行不在表格末尾
【发布时间】:2012-08-15 01:09:29
【问题描述】:

我有一个 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 新手。

【问题讨论】:

  • 这不是很好,但是jsfiddle.net/n7Gup/3
  • 我不明白你想在哪里添加它?
  • 为什么不直接指定要添加的行,然后用after 或在开头添加prepend()
  • 匿名 - 我想将其添加到具有“中度风险活动总数”的行上方
  • 谢谢@ahren - 这是一个好的开始。你知道是否可以修改你所做的,以便创建的新行可以让所有输入字段为空。还有一种方法可以让“新行”按钮只出现一次,并且总是在活动输入的最后一行。例如,最初只有一行,但如果您单击“新行”按钮,则会在初始行下方创建第二行,并且“新行”按钮现在只会出现在这个新创建的行上。

标签: javascript jquery html-table


【解决方案1】:

这里有一个解决方案

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

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

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

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多