如何重新索引 HTML 元素名称和 ID

How to re-index HTML element name and ids?

本文关键字:ID 元素 何重新 索引 HTML      更新时间:2023-09-26

我正在创建一个动态表单。 当我单击"删除"按钮时,我希望将元素重新索引。 例如,如果我创建 5 个元素 items1、items2、items3、items4、items5 并删除 items3,我希望将其他四个元素从 1 重新索引到 4,如 items1、item2、item3、item4。

这是我的代码:

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">

试试这个:

jQuery('select.items').each(function(index){
    this.id = 'items' + index + 1;
    this.setAttribute("name",this.id);
});
您可以通过

attr 设置 id 来执行此操作

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

你可以这样做:

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