使用附加复制表行 – 想创建唯一ID
我有一个表单,其中包含一个包含项目行的表供用户填写。我目前已设置它,以便用户可以添加额外的行,以防他们需要添加更多信息。
这非常有效,但我想知道是否有办法为每个克隆字段生成唯一的ID。
My function is currently this: function addTableRow(table) { $(table).append($(table + ' tr:last').clone()); return true; }
并从表id中传入的onclick调用。
表行包含以下信息:
ft
我想要的是当我克隆id的行增加1时所以下一行会有id:
txtBarnParts2,txtBarnWidth2,txtBarnRemarks2 ……等等。
有没有办法做到这一点?
谢谢!
var $newTr = $(table + ' tr:last').clone(); var newIndex = $newTr.index() + 1; $newTr.find('[id]').each(function () { this.id = this.id.replace(/[0-9]+$/e, newIndex); }); $(table).append($newTr);
试试这个。 需要jQuery 1.4或更高版本。
根据您的使用情况,我假设table
存储带有哈希的ID,如"#myTable"
。
function addTableRow(table) { var $last = $(table + ' tr:last'); var num = $last.index() + 1; // If the IDs in each row are indexed starting // with 1, then you would need "+ 2" instead $last.clone().find(':input[id]') .attr('id', function(i,current) { return current.replace(/\d+$/, num); }) .end().appendTo(table); return true; }
这会在新(克隆)行上执行.find()
,搜索具有ID属性的input
元素。 然后它将一个函数传递给.attr()
方法,该方法用新的数字替换当前的结束数字。
- http://api.jquery.com/index/
- http://api.jquery.com/attr/
- http://api.jquery.com/end/
- http://api.jquery.com/appendTo/
编辑:错过了.attr()
调用中的逗号。 固定。
编辑:有.clone()
在错误的地方。 固定。
var i = 1 function addTableRow() { $("table").append($("table tr:last").clone()); $("table tr:last input").attr("name", $("table tr:first input").attr("name")+i); i++; })
这与名字一起使用。 类似的将与id一起使用。
这是通用function
var indexCloneTableLastRowSelect = 1; var indexCloneTableLastRowInput = 1; var forEachElementItrateOnce = 1; function cloneTableLastRow_(tableID_) { tableID_ = '#' + tableID_; // copy|clone last row $(tableID_).append($(tableID_ + " tr:last").clone()); $(tableID_ + " tr:last").each(function (){ $(tableID_ + " tr:last select").attr("name", function() { if (forEachElementItrateOnce == 1){ indexCloneTableLastRowSelect++; } this.name = this.name.replace(/[0-9]+$/, indexCloneTableLastRowSelect); this.id = this.id.replace(/[0-9]+$/, indexCloneTableLastRowSelect); forEachElementItrateOnce = 0; }) $(tableID_ + " tr:last input").attr("name", function() { if (forEachElementItrateOnce == 1){ indexCloneTableLastRowInput++; } this.name = this.name.replace(/[0-9]+$/, indexCloneTableLastRowInput); this.id = this.id.replace(/[0-9]+$/, indexCloneTableLastRowInput); forEachElementItrateOnce = 0; }) }) forEachElementItrateOnce = 1; }