[javascript] jQuery clone () 및 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 검색

ID가 klon--5같지만 스크램블 된 (순서가 아님) 많은 요소가 있다고 가정 해 보겠습니다 . 여기서는 또는 로 갈 수 없으므로 가장 높은 ID를 검색하는 메커니즘이 필요합니다.:last:first

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>


답변

업데이트 :로코 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");


답변

일반화 된 솔루션을 만들었습니다. 아래 함수는 복제 된 개체의 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;
}


답변

이것도 작동합니다

 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>


답변

$('#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>


답변