如何克隆和更改ID? [英] How to clone and change id?
本文介绍了如何克隆和更改ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要克隆 id,然后在它后面添加一个数字,例如 id1
、id2
等.每次点击 clone 时,您都将克隆放在最新的之后身份证号码.
I need to clone the id and then add a number after it like so id1
, id2
, etc. Every time you hit clone you put the clone after the latest number of the id.
$("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>
假设您有许多 ID 为 klon--5
之类的元素,但它们是乱码(不按顺序).这里我们不能去:last
或:first
,因此我们需要一种机制来检索最高ID:
Say you have many elements with IDs like klon--5
but scrambled (not in order). Here we cannot go for :last
or :first
, therefore we need a mechanism to retrieve the highest ID:
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>
这篇关于如何克隆和更改ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文