更新: 正如 Roko C.Bulijan指出的。.你需要使用。在选定的 div 之后插入它。如果希望将更新后的代码添加到末尾,而不是在多次克隆时开始,请参见更新后的代码。译自: 美国《科学》杂志网站(http://jsfiddle.net/HGtmR/4/rel = “ noReferrer”)
密码:
var cloneCount = 1;;
$("button").click(function(){
$('#id')
.clone()
.attr('id', 'id'+ cloneCount++)
.insertAfter('[id^=id]:last')
// ^-- Use '#id' if you want to insert the cloned
// element in the beginning
.text('Cloned ' + (cloneCount-1)); //<--For DEMO
});
试试看,
$("#id").clone().attr('id', 'id1').after("#id");
如果你想要一个自动计数器,请看下面,
var cloneCount = 1;
$("button").click(function(){
$("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
});
$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id="cloneDiv">CLICK TO CLONE</button>
<div id="klon1">klon1</div>
<div id="klon2">klon2</div>
$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});