반응형
ID를 복제하고 변경하는 방법은?
ID를 복제한 다음에 번호를 추가해야 합니다.id1
,id2
, 등. 클론을 누를 때마다 클론은 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를 검색할 수 있는 메커니즘이 필요합니다.
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>
업데이트: 로코 C.Bulijan은 지적했습니다..선택한 div 뒤에 삽입하려면 .insertAfter를 사용해야 합니다.여러 번 복제할 때 시작하는 대신 끝까지 추가하려면 업데이트된 코드를 참조하십시오. 데모
코드:
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");
});
이것이 저에게 가장 간단한 해결책입니다.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
이것도 효과가 있습니다.
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>
일반화된 솔루션을 만들었습니다.아래 기능은 복제된 개체의 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;
}
$('#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>
언급URL : https://stackoverflow.com/questions/10126395/how-to-clone-and-change-id
반응형
'programing' 카테고리의 다른 글
mariadb의 json(긴 텍스트) 필드에서 데이터 추출 (0) | 2023.10.24 |
---|---|
클라이언트 통계 테이블(Microsoft SQL Server Management Studio) (0) | 2023.10.24 |
플러그인 없이 워드프레스에서 부트스트랩 회전목마 통합 (0) | 2023.10.24 |
Oracle 저장 프로시저의 "Boolean" 파라미터 (0) | 2023.10.24 |
JavaScript를 트리거하는 링크를 클릭하면 웹 페이지가 맨 위로 스크롤되지 않도록 하려면 어떻게 해야 합니까? (0) | 2023.10.24 |