【发布时间】:2021-01-10 23:03:56
【问题描述】:
我有一个后续代码 (LINK) 可以很好地克隆一个块 html 结构。问题是我需要将新添加的结构修复到 DOM。但是当我刷新页面时,我丢失了添加的块。如何永久添加新添加的块?
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone() {
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove() {
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
body {
padding: 10px;
}
.clonedInput {
padding: 10px;
border-radius: 5px;
background-color: #def;
margin-bottom: 10px;
}
.clonedInput div {
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
【问题讨论】:
-
以后,避免链接到代码,但不要嵌入任何代码。您应该收到验证错误。看起来你通过将链接文本包装在刻度标记内来解决这个问题,它甚至不会呈现链接并且实际上隐藏它不被点击......
-
为了保存您动态添加的内容,您需要在关闭窗口之前存储状态。您将需要能够保存状态并回放它。 jQuery 不会为您执行此操作。您将需要自己的算法或插件。
标签: javascript html jquery dom clone