2012-04-12 12 views
91

id를 복제 한 후 id1, id2 등의 숫자를 추가해야합니다. 복제 할 때마다 최신 ID 번호 뒤에 복제본을 넣어야합니다.JQuery clone() 및 id 변경 방법

$("button").click(function(){ 
    $("#id").clone().after("#id"); 
    }); 

답변

151

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

+1

+1 작업 데모 :) 그리고 내 대답을 살펴 줘서 고마워. 게시물을 업데이 트했습니다 또한 작업 데모를 추가 http://jsfiddle.net/HGtmR/4/ –

+0

그것은 또한 현재 ID를 div 제거 div 안에 버튼을 가질 수 있습니까? – user1324780

+1

@ user1324780 예, 가능하지만 새로운 질문으로 게시해야합니다. 어쨌든 단서는'.closest (div [id^= id])'와'.remove'를 찾아내는 것이다. –

39

업데이트 : 지적Roko C.Bulijan으로 .. 당신이 선택한 DIV 후를 삽입 .insertAfter를 사용해야합니다. 여러 번 복제 할 때 시작하는 대신 끝에 추가하려는 경우 업데이트 된 코드를 참조하십시오. DEMO

코드 :

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"); 
    }); 
+18

코드에서''id '+ ++ id'를 사용하지 못했습니다. – Blazemonger

+0

실용적인 데모를 제공해 주시겠습니까? http://jsfiddle.net/HGtmR/ –

+0

@ RokoC.Buljan 맞습니다.하지만 질문은 복제 된 요소의 속성을 변경하는 방법 이었으므로'.after'를 알아 내지 못했습니다. 업데이트 된 답변보기 –

3

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