1

我有一个 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;
});

导致错误说我不能在空对象上调用“替换”,因此似乎找不到名称属性。

谁能看到我做错了什么?谢谢!

4

4 回答 4

2

问题来自您声明的这一部分:add(element)

看,element指的是完整的行,并且行没有名称属性。您只想对具有 name 属性的行内的输入进行操作,因此您应该从代码中删除该部分:

$(element).find("[name]").each(function() {
    this.name = this.name.replace(/\d+$/, "")+counter;
});
于 2013-08-20T17:18:54.083 回答
1

用于$(this).attr('name');获取和设置名称属性。

完整的线路:

$(this).attr('name',$( this).attr('name').replace(/\d+$/, "")+counter);
于 2013-08-20T17:07:06.763 回答
1

HTML 元素没有name属性。相反,您需要将其作为属性访问:

this.setAttribute('name', this.getAttribute('name').replace(/\d+$/, "")+counter);

工作演示

于 2013-08-20T17:04:36.543 回答
0

尝试这个

$(element).find("[name]").add(element).each(function() {
    this.attr("name",this.attr('name').replace(/\d+$/, "")+counter) ;
});
于 2013-08-20T17:11:05.837 回答