【发布时间】:2012-08-15 01:09:29
【问题描述】:
我有一个 HTML 表格,并希望允许用户单击按钮来添加新行,但新行不会添加到表格末尾,而是添加到最后一行输入字段之后。
我在以下位置设置了一个示例 JSFiddle:
我有一个新行按钮,但它没有克隆输入的最后一行(即新行按钮所在的行)。我需要修改它,以便在这些输入行的最后一个之后插入一个新行。
这是我从在线教程中找到的脚本:
$(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