2012-06-04 71 views
0

我使用jQuery 1.7.2克隆了一組表單輸入元素。每個輸入元素都有一個id屬性。我希望克隆的元素使用與源元素相同的id屬性,但附加一個數字以使它們唯一。使用克隆的jQuery對象添加號碼以增加id屬性的值

我的代碼是這樣的:

// Add additional author fields 
    jQuery('#addanotherauthor a').click(function() { 
     // Clone 'other author' group of fields 
     var markUpToClone = jQuery('.other-authors').clone(); 
     // Set all input values of cloned mark-up to empty, remove 'disabled' attribute 
     markUpToClone.find('input').val('').removeAttr('disabled'); 
     // Ensure cloned inputs have unique id attributes 
     var numberOfAdditionalAuthors = $('.other-authors').length.toString(); 
     markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors); 
     // Append emptied clone 
     jQuery('#otherauthorscontainer').append(markUpToClone); 
     return false; 
    }); 

當我運行此,克隆元素的id屬性成爲「undefined1」,「undefined2」等有趣的是,如果我這樣做:

markUpToClone.find('input').attr('id', numberOfAdditionalAuthors); 

它返回一個正確遞增的數字的id。如果我這樣做:

markUpToClone.find('input').attr('id', $(this).attr('id')); 

它返回一個與源值相同的ID。但是,當我試圖把兩個在一起:

markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors); 

我得到'undefined1'的問題。

任何人都可以看到這是失敗,並提出修復?

謝謝大家!

+0

做你點擊了''標籤有'ID',我覺得沒有 – thecodeparadox

+0

號我想'$(本).attr(「ID」)'在這種情況下會獲取克隆中輸入的id,而不是被點擊的'a'標籤的id。如何將'numberOfAdditionalAuthors'追加到所有克隆輸入標籤的id屬性? – Dan

回答

2

您對this的使用不在上下文中。現在用attr(function(index, attr){})管理ID的

// Add additional author fields 
    jQuery('#addanotherauthor a').click(function() { 
     // Clone 'other author' group of fields 
     var markUpToClone = jQuery('.other-authors').clone(); 
     // Set all input values of cloned mark-up to empty, remove 'disabled' attribute 
     var numberOfAdditionalAuthors = $('.other-authors').length/*.toString()*/;// toString() not needed 
     markUpToClone.find('input').val('').removeAttr('disabled') 
     // Ensure cloned inputs have unique id attributes 
       .attr('id', function(i, id){ 
         return id + numberOfAdditionalAuthors; 
       }); 


     // Append emptied clone 
     jQuery('#otherauthorscontainer').append(markUpToClone); 
     return false; 
    });