2016-12-09 34 views
-1

我使用jQuery clone()方法克隆形式,並通過1

一切形式的更新輸入值的「id」屬性增量會完美的,但我我很好奇$(this)this

在克隆() - > each()方法,而更新輸入id我所面臨的問題時,我更新值一樣,如:

this.id=newId;那麼它的工作和更新id屬性

但如果我用$(this).attr(oldId,newId)然後它不工作

如果我使用var old=newId然後還其不工作

我已經提到thisthis但仍然困惑爲什麼最後兩種方法不起作用。

全碼:

var clonedTemplate = $(".form-section .row:first").clone(); 
var index = 0; 
$("body").on('click', '.add', function() { 
    index++; 
    var formSection = clonedTemplate.clone().find(':input').each(function() { 
     var oldId = $(this).attr('id'); 
     var newId = oldId + "_" + index; 
     this.id=newId; //its working and updating id attribute 
     $(this).attr(oldId,newId) // not working 
     oldId=newId; // not working 
    }); 
    formSection.end().appendTo('.form-section'); 
}); 

任何幫助/建議或更好的解決方案,將不勝感激。

+1

'attr'需要'attributeName'和'value'。所以我想你會想'$(this).attr('id',newId)' –

回答

2

你需要在你的改變,而不是它的值,因此這條線的屬性的名稱通過

$(this).attr(oldId,newId) 

需求,成爲

$(this).attr('id',newId) 
+0

這真是個愚蠢的錯誤..謝謝 – Sky