我需要克隆id,然后在后面添加一个数字,比如id1
,id2
,等等。每次你点击克隆,你就把克隆放在最新的id后面。
$("button").click(function() {
$("#id").clone().after("#id");
});
发布于 2019-03-07 20:32:40
这是对我有效的最简单的解决方案。
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
发布于 2020-04-01 00:41:11
这也行得通
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>
发布于 2016-09-08 19:38:01
我已经创建了一个通用的解决方案。下面的函数将更改克隆对象的ids和名称。在大多数情况下,您需要行号,因此只需向对象添加"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;
}
https://stackoverflow.com/questions/10126395
复制相似问题