Javascript 如何 jQuery clone() 并更改 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10126395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to jQuery clone() and change id?
提问by user1324780
I need to clone the id and then add a number after it like so id1
, id2
, etc. Everytime you hit clone you put the clone after the latest number of the id.
我需要克隆的ID,然后添加一个数字后,像现在这样id1
,id2
等每次你打你把克隆的最新数的ID后,克隆。
$("button").click(function() {
$("#id").clone().after("#id");
});
回答by Roko C. Buljan
$('#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>
Scrambled elements, retrieve highest ID
加扰元素,检索最高ID
Say you have many elements with IDs like klon--5
but scrambled (not in order). Here we cannotgo for :last
or :first
, therefore we need a mechanism to retrieve the highest ID:
假设您有许多 ID 类似klon--5
但已加扰(不按顺序)的元素。在这里,我们不能使用:last
or :first
,因此我们需要一种机制来检索最高 ID:
const $all = $('[id^="klon--"]');
const maxID = Math.max.apply(Math, $all.map((i, el) => +el.id.match(/\d+$/g)[0]).get());
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>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
回答by Selvakumar Arumugam
Update:As Roko C.Bulijanpointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO
更新:正如Roko C.Bulijan指出的那样......你需要使用 .insertAfter 将它插入到选定的 div 之后。如果您希望将其附加到末尾而不是在多次克隆时开始,请参阅更新的代码。演示
Code:
代码:
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
});
Try,
尝试,
$("#id").clone().attr('id', 'id1').after("#id");
If you want a automatic counter, then see below,
如果你想要一个自动计数器,然后看下面,
var cloneCount = 1;
$("button").click(function(){
$("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
});
回答by Hassan Mehmood
This is the simplest solution working for me.
这是对我有用的最简单的解决方案。
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
回答by agxhdf
This works too
这也有效
var i = 1;
$('button').click(function() {
$('#red').clone().appendTo('#test').prop('id', 'red' + i);
i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="test">
<button>Clone</button>
<div class="red" id="red">
</div>
</div>
<style>
.red {
width:20px;
height:20px;
background-color: red;
margin: 10px;
}
</style>
回答by Piyush Balapure
I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.
我已经创建了一个通用的解决方案。下面的函数将更改克隆对象的 id 和名称。在大多数情况下,您将需要行号,因此只需向对象添加“data-row-id”属性即可。
function renameCloneIdsAndNames( objClone ) {
if( !objClone.attr( 'data-row-id' ) ) {
console.error( 'Cloned object must have \'data-row-id\' attribute.' );
}
if( objClone.attr( 'id' ) ) {
objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
}
objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
objClone.find( '[id]' ).each( function() {
var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
$( this ).attr( 'id', strNewId );
if( $( this ).attr( 'name' ) ) {
var strNewName = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
strName = strName.replace( /[\[\]']+/g, '' );
var intNumber = parseInt( strName ) + 1;
return '[' + intNumber + ']'
} );
$( this ).attr( 'name', strNewName );
}
});
return objClone;
}
回答by Hezal M. Tank
$('#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>