我有一个 html 表单的表格,其中包含一个表格,每次单击按钮时都会向该表格添加一行。添加每一行时,我希望新行(有四个)中每个字段的名称和 ID 从第一行的“Id.0”更新为第二行的“Id.1”,然后“Id.2"在第三个等中。我可以用 id 来完成这个没有问题,使用
var next=$("#QualificationRequirements tr:last").clone();
fixIds(next,nexdex);
nexdex++;
$("#QualificationRequirements").append(next);
function fixIds(element, counter) {
$(element).find("[id]").add(element).each(function() {
this.id = this.id.replace(/\d+$/, "")+counter;
}
}
但是我发现相同的逻辑不适用于 name 属性,并且
$(element).find("[name]").add(element).each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
导致错误提示我无法在空对象上调用“replace”,因此似乎未找到 name 属性。
谁能看出我做错了什么?谢谢!
最佳答案
问题来自您声明的这一部分:add(element)
看,element
指的是完整的行,行没有名称属性。您只想对行内具有名称属性的输入进行操作,因此您应该从代码中删除该部分:
$(element).find("[name]").each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
关于javascript - 更改附加表行字段的名称 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18340890/