DOM元素上动态创建的ID的排序一致性
Sorting consistency of dynamically created IDs on DOM Elements
我的应用程序成功地创建了元素,并为它们分配了不同的(不断增加的)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')
}
});
我使用的计数器可以整齐地递增quantity
和description
的ID,比如:
quantity0
quantity1
quantity2
..等等,但是一旦调用以下脚本。。。
//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
,并"更新"每个Add
和Delete
上的ID
编号。
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- difference between '$(<%= DDL.ID %>) & $('
- 使用Javascript获取所选选项ID
- 根据id将json数组组合为一个json数组
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 对id以某个字符串开头的元素进行计数
- 如果元素's的ID以数字开头
- 通过id和class属性获取元素
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 使用当前日期生成随机id
- Javascript-ID冲突的几率
- Href:当前DIV中的目标ID
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- Javascript复选框函数:;缺少:在属性id之后"
- Twitter引导程序Typeahead-Id&标签
- 如何与特定ID交谈
- chart.series[id].remove()无法刷新高位图表/高位股票中其他系列的图例属性
- 如何在速度模板中获取LiferayPortlet实例id
- 在保持元素一致性的同时旋转数组元素的最佳方式'id
- DOM元素上动态创建的ID的排序一致性