2013-10-11 38 views
0

我正在創建一個動態表單。當我點擊刪除按鈕時,我想要重新編制索引元素。例如,如果我創建了5個元素項目1,項目2,項目3,項目4,項目5和我刪除項目3,我希望其他四個元素從​​1到4重新索引,如項目1,項目2,項目3,項目4。如何重新索引HTML元素名稱和ID?

這裏是我的代碼:

jQuery(document).on("ready", function() { 
    initAddRows(); 
}); 

function initAddRows() { 
    var template = jQuery("#template"), 
     dataRows = jQuery("#dataRows") 

    jQuery("#btnAdd").on("click", function() { 
     var newRow = template.clone(true, true), 
      fieldRows = dataRows.find(".fieldRow"), 
      rowNumber = fieldRows.length + 1; 

     newRow.attr('id', 'row' + rowNumber).find('[id]').each(function() {    
      jQuery(this).attr("id", jQuery(this).attr("id") + rowNumber); 
      jQuery(this).attr("name", jQuery(this).attr("name") + rowNumber); 
      $('#itemscounter').val(+rowNumber); 
     });  
     fieldRows.filter(":last").after(newRow); 
    }); 

    dataRows.on("click", ".remove", function() {      
     jQuery(this).parent().remove(); 
    }); 
} 

這裏是我的html代碼:

<select id="items" class="items" style="width:127px; float:left;" name="items"> 
<select id="items2" class="items" style="width:127px; float:left;" name="items2"> 
<select id="items3" class="items" style="width:127px; float:left;" name="items3"> 
<select id="items4" class="items" style="width:127px; float:left;" name="items4"> 
<select id="items5" class="items" style="width:127px; float:left;" name="items5"> 
+0

一個工作撥弄將使它easyer – Randy

回答

1

您可以通過attr所設置id

$('select.items').each(function(index){ 
if ($(this).attr("id") != 'items') { 
    $(this).attr("id","items" + (index + 1)); 
} 
}); 
+0

你的代碼的工作,但我想在第一個字段的名稱=項目和id =項目 –

+0

我已經編輯我的回答對你 –

+0

沒有變化沒有爲我工作 –

1

試試這個做到這一點:

jQuery('select.items').each(function(index){ 
    this.id = 'items' + index + 1; 
    this.setAttribute("name",this.id); 
}); 
0

你可以這樣做:

$('.items').attr('id', function (index, oldID) { 
    return 'items' + (parseInt(index, 10) + 1); 
}).attr('name', function (index, oldName) { 
    return 'items' + (parseInt(index, 10) + 1); 
});