jQuery 添加新的表行不在表的末尾
jQuery Adding New Table Row Not at the End of the Table
我有一个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(),克隆它(带有事件),删除原始中的新行按钮(您可能需要用删除按钮替换它),然后在原始之后插入克隆。
此外,现在您可能不需要对传递给单击处理程序的表对象的引用(不过我将其保留在代码中)。
相关文章:
- 正在SharePoint 2013母版页中添加JQuery移动文件
- JQuery添加元素需要在我的js之前再次添加JQuery脚本
- 使用.on动态添加jquery/js不知道的html元素
- Rails资产管道-只向head添加jquery
- 如何在XHTML中添加jQuery CDN回退
- 添加JQuery UI在Meteor中添加对象后可调整大小
- 添加jquery Datepicker后,文本框的初始值不会显示
- 添加Jquery验证后,Jquery日期选择器无法工作
- 如何在谷歌博客中添加jQuery而不修改模板
- 从服务器端添加jQuery函数
- 如何在jQuery.awesomeCloud.plugin上添加jQuery工具提示功能
- 动态添加jquery ajax选项
- 正在添加JQuery淡入淡出代码
- 添加 jQuery UI 后,从表中删除行的函数不起作用
- 如何动态添加 jQuery 移动弹出效果到链接
- 如何在 mytemplate 中添加 Jquery
- 在页面加载后动态添加 jquery 日期选择器
- 这是在一个项目中添加Jquery和Angularjs的正确方法
- 滚动到页面末尾后添加 JQuery 微调器
- 在图像不起作用的 src 中添加 jQuery 变量