jQuery - 确保ID在插入的标记中是唯一的

时间:2017-03-29 13:40:32

标签: javascript jquery html

我有以下标记:

<div id="section">
    <input type="text" id="myInput">
</div>

我试图使用jQuery html()after()方法在自身之后插入此标记的html内容:

var newSection = $('#section').html();
$('#section').after(newSection);

所以我最终会得到这样的结论:

<div id="section">
    <input type="text" id="myInput">
</div>
<input type="text" id="myInput">

有没有办法可以确保输入的ID是唯一的?对于已插入的输入,我更喜欢“myInput2”之类的东西。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用JavaSparkContext newcontext = new JavaSparkContext(session.sparkContext()); Map<String, String> readOverrides = new HashMap<String, String>(); readOverrides.put("collection", "details"); readOverrides.put("readPreference.name", "secondaryPreferred"); ReadConfig readConfig = ReadConfig.create(newcontext).withOptions(readOverrides); MongoSpark.load(newcontext,readConfig); 检查元素是否存在。然后你可以使用while循环来增加最后的数字。

$(selector).length

答案 1 :(得分:1)

这是一种保持代码相同的方法,但添加了具有唯一ID的新元素,特别是“myInput2”用于第二次执行,或者“myInputN”用于添加任何数字输入:

var newSection = $("#section").html();
//create new element with unique ID
newSection = $(newSection).attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("#section").after(newSection);

要确定下一个唯一ID,我们只需查询以“myInput”

开头的所有输入标记

如果您确实需要带有输入的新部分,以便输入字段一个接一个地出现(在彼此之上),您可以使用以下方法创建一个具有唯一ID的新部分,并包含一个新的输入ID:

//Create a new section by cloning the first section
var newSection = $("#section").clone();
//Set the new unique ID for the section
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
//Set the new unique ID for child input element
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
//Add the new section last so each section appears in order by ID
$("div[id^=section").last().after(newSection);