我有一个动态html表/表单,它有两个按钮来向表添加一行。一个按钮将行添加到表的末尾,并适当地增加输入id。另一个按钮用于在当前行之前插入一行…它可以这样做,直到我尝试让它增加id。我当前的jquery代码适当地更新了id,但去掉了标签,导致所有输入字段被粉碎到表的单个单元格中。我在下面包含了我现有的代码片段…我错过了什么?
链接到小提琴
jquery代码:$(document).on('click', 'button.insertbutton', function () {
var rowCount = $('#orderDetail tr').length;
alert(rowCount);
$(this).closest('tr').before($(this).closest('tr').find('input')
.each(function() {
$(this).attr({
'id': function(_, id) {
var regex = /[a-zA-Z]+/
return id.match(regex) + rowCount },
//'name': function(_, name) { return name + rowCount },
'value': '',
});
})
).clone(true);
return true;
});
我怀疑问题是在我迭代输入项然后克隆回行的部分。
如有任何指导,将不胜感激。
编辑包括小提琴作为推荐…谢谢你的推荐。
我能够通过将操作分解为两个步骤来解决克隆和增量ID,而不是试图在一行中完成任务。插入和更新id的jquery代码如下:
$(document).on('click', 'button.insertbutton', function () {
var rowCount = $('#orderDetail tr').length;
$(this).closest('tr').before($(this).closest('tr').clone());
$(this).closest('tr').find('input').each(function() {
$(this).attr({
'id': function(_,id) {
var regex = /[a-zA-Z]+/
return id.match(regex) + rowCount },
'value': '',
})
})
return true;
});
我希望这对将来的人有帮助