جاوااسکریپت - چگونه یک کپی بسازیم و شناسه را تغییر دهیم؟
من نیاز دارم که شناسه را کلون کنم و سپس یک عدد بعد از آن اضافه کنم به این صورت id1، id2، و غیره. هر بار که روی کلون کلیک میکنید، کلون را بعد از آخرین شماره شناسه قرار میدهید.
$("button").click(function() {
$("#id").clone().after("#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>عناصر در هم، بالاترین شناسه را بازیابی کنید
فرض کنید عناصر زیادی با شناسههایی مانند klon--5 دارید اما به هم ریختهاند (نه مرتب). در اینجا نمیتوانیم از :last یا :first استفاده کنیم، بنابراین به مکانیزمی نیاز داریم تا بالاترین شناسه را بازیابی کنیم:
const all = document.querySelectorAll('[id^="klon--"]');
const maxID = Math.max.apply(Math, [...all].map(el => +el.id.match(/\d+$/g)[0]));
const nextId = maxID + 1;
console.log(`New ID is: ${nextId}`);<div id="klon--12">12</div>
<div id="klon--34">34</div>
<div id="klon--8">8</div>پاسخ شماره ۲
بهروزرسانی: همانطور که Roko C.Bulijan اشاره کرد.. شما نیاز دارید از .insertAfter استفاده کنید تا آن را بعد از div انتخابشده وارد کنید. همچنین کد بهروزشده را ببینید اگر میخواهید وقتی چندین بار کلون شده است، به جای ابتدا، در انتها اضافه شود. دمو
کد:
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");
});
