我正在創建一個動態表單。當我點擊刪除按鈕時,我想要重新編制索引元素。例如,如果我創建了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">
一個工作撥弄將使它easyer – Randy