我有一个表单,在我的表单中有一个加号按钮用于添加 div,最后我会将该 div 的列表发送到我的 Controller 。
$(“#addDiv”).click(function() {
$(“#myForm div# section_0).clone().appendTo(“#myForm”);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id=“myForm”>
<div id=“section_0”>
//some tags here
</div>
<button id=“addDiv” class=“btn btn-primary”>add</add>
</form>
复制该 div 没有任何问题,但我需要为该 div 附加一个新的 id 并增加 1。 如果有人可以提供帮助,我将不胜感激
最佳答案
设置一个全局变量 globalSectionId
以在每次点击时递增,并在每次 clone()
时替换属性 id
globalSectionId = 0;
$("#addDiv").click(function (){
$("#myForm div#section_0").clone().attr({id:`section_${++globalSectionId}`}).appendTo("#myForm");
// clone(). and set the new id with the .attr() - Thx @Phil
});
我做了一个 JSFiddle 工作:https://jsfiddle.net/4efkhdba/
globalSectionId = 0;
$("#addDiv").click(function (){
$("#myForm div#section_0").clone().attr({id:`section_${++globalSectionId}`}).appendTo("#myForm");
// clone(). and set the new id with the .attr() - Thx @Phil
console.log('the new id:'+globalSectionId)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myForm">
<div id="section_0">
CLONE DIV!
</div>
<button type="button" id="addDiv" class="btn btn-primary">add</add>
</div>
关于javascript - 如何在javascript中复制标签时增加ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56034571/