DOM元素上动态创建的ID的排序一致性

Sorting consistency of dynamically created IDs on DOM Elements

本文关键字:ID 一致性 排序 创建 元素 动态 DOM      更新时间:2024-02-09

我的应用程序成功地创建了元素,并为它们分配了不同的(不断增加的)ID。

现在,我的问题依赖于当用户删除这些元素时(因为他们可以选择删除和创建),这些ID的一致性会被破坏,因此我的应用程序运行不好。

这个Fiddle代表了我迄今为止所拥有的。只是一个文本框,可以根据用户的需要多次在collapsible中附加其值和其他一些元素(出于某种原因,我的fiddle不会增加alert的值,但它在我的平台上运行良好)。

SCRIPT(抱歉txt变量太长)

$('#Add').click(function () {
if ($("#MedNameStren").val() != "") {
    var value = $("#MedNameStren").val();
    var noOfMeds = $('#NoOfMedicines').val();
    //to check current value
    alert(noOfMeds);
    var text = '<div data-role="collapsible" data-collapsed="true" data-iconpos="left" data-content-theme="e">' + '<h2>' + desc + '</h2>' + '<div class="ui-grid-a">' +          '<div class="ui-block-a" style="width:25%; margin-right:3%;">' + '<input id="quantity' + noOfMeds + '" class="quantity" type="text" placeholder="Quantity" />' + '</div>' + '<div class="ui-block-b" style="width:70%; margin-right:2%;"">' + '<textarea id="directions' + noOfMeds + '" class="directions" cols="40" rows="4" placeholder="Directions given by your GP." ></textarea>' + '</div>' + '</div>' + '<button key="' + vpid + '">Remove</button>' + '</div>';
    $("#medListLi").append(text);
    $('button').button();
    $('#medListLi').find('div[data-role=collapsible]').collapsible();
    $('#medListLi li').listview("refresh");
    $('#medListLi').trigger("create");
    document.getElementById("manuallyName").value = "";
    noOfMeds++
    $("#NoOfMedicines").val(noOfMeds);
}
else {
         alert('Please Provide Medicine Name')
}
});

我使用的计数器可以整齐地递增quantitydescription的ID,比如:

quantity0quantity1quantity2..等等,但是一旦调用以下脚本。。。

//Deletes colapsible sets (Medicines) from the selected List
$('#medListLi').on('click', 'button', function (el) {
$(this).closest('div[data-role=collapsible]').remove();
var key = $(this).attr('key');
localStorage.removeItem(key);
var noOfMeds = $('#NoOfMedicines').val();
noOfMeds--
$("#NoOfMedicines").val(noOfMeds);
//location.reload();
});

根据哪个元素(collapsible)被删除,ID停止一致。例如,如果删除了带有id="quantity1"collapsible,则计数器将返回到1(当前为2),并且在下一次添加时,相应的collapsible将获得已经占用的id,不幸的是,我不需要发生这种情况。

也许我让这听起来更复杂,但如果可能的话,我会感谢任何解决这个问题的建议或想法。

如果需要更多信息,请告诉我。

我注意到,创建和删除动态IDs是可以完成的,但要保持这些IDs的一致性可能非常困难

我通过简单地创建一个函数来解决我自己的问题,该函数将根据list中的collapsibles数量来计算IDs,并"更新"每个AddDelete上的ID编号。