2013-08-20 29 views
1

我有一個html表格,其中包含一個表格,每次單擊按鈕時都會添加一行。當添加每一行時,我希望新行中的每個字段的名稱和id(有四個)從第一行中的「Id.0」更新爲第二行中的「Id.1」,然後「 ID.2" 第三,等我可以通過ID做到這一點使用更改附加表格行字段的名稱jQuery

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; 
}); 
沒問題

會導致一個錯誤,表示我無法在空對象上調用「替換」,因此看起來名稱屬性未找到。

任何人都可以看到我做錯了什麼?謝謝!

+2

每當你得到一個錯誤,請提供。 –

回答

2

問題來自於您的發言的這一部分:add(element)

見,element指的是完整的行和列沒有名稱屬性。你只是想讓有name屬性的行內投入行動,所以你應該從你的代碼中刪除部分:

$(element).find("[name]").each(function() { 
    this.name = this.name.replace(/\d+$/, "")+counter; 
}); 
1

HTML元素上沒有name屬性。相反,你需要訪問它作爲一個屬性:

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

Working Demo

1

使用$(this).attr('name');來獲取和設置的name屬性。

全部產品線:

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

這不會起作用,因爲在'each()'函數中,'this'是指HTML元素,而不是jQuery對象,所以試圖使用'attr()'會引發錯誤。 – cfs

+0

你說得對,更正了。 –

0

試試這個

$(element).find("[name]").add(element).each(function() { 
    this.attr("name",this.attr('name').replace(/\d+$/, "")+counter) ; 
});