2012-08-15 134 views
0

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

我设置一个样品的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); 
    }; 
}); 

所创建可以将所有输入的新行字段为空的用户将再次启动。还有一种方法可以让New Row按钮只出现一次,并且这将始终在最后一行活动输入中。例如,最初只有一行,但如果您单击新建行按钮,则会在最初的行下创建第二行,而新建行按钮现在只会出现在此新创建的行上。

感谢任何帮助 - 我是一个在这个阶段的Javascript新手。

+1

这不是很好,但http://jsfiddle.net/n7Gup/3/ – ahren 2012-08-15 01:13:58

+0

我不明白你要添加它在哪里? – Anonymous 2012-08-15 01:25:51

+1

为什么不要在你想添加它并在'after'后面添加它,或者在'prepend()'开始时添加它? – Anonymous 2012-08-15 01:26:30

回答

1

这里是一个解决方案

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

基本上只需将引用传递到按钮点击,并从那里在工作表中出你的定位 - 保存参考目前最后一行(使用最接近(),克隆它(带有事件),删除原来的新行按钮(你可能需要用一个删除按钮替换它),然后在原始文件后插入克隆。对传递给你的点击处理程序的表对象的引用(我把它留在了c中尽管)。

相关问题