2012-08-15 129 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中儘管)。

相關問題