136

IDのクローンを作成し、その後に番号を追加する必要があります。たとえば、cloneを押すたびに、IDの最新の番号の後にクローンを配置しますid1id2

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

6 に答える 6

228

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

IDklon--5がスクランブルされている(順番になっていない)要素がたくさんあるとします。ここでは、またはに進むことができないため、最高のIDを取得するメカニズムが必要です。:last:first

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>

于 2012-04-12T15:44:51.453 に答える
47

更新:Roko 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");
   }); 
于 2012-04-12T15:09:30.390 に答える
8

これは私にとって最も簡単な解決策です。

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
于 2019-03-07T12:32:40.433 に答える
4

これも機能します

 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>

于 2020-03-31T16:41:11.127 に答える
2

一般化されたソリューションを作成しました。以下の関数は、複製されたオブジェクトの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;
}
于 2016-09-08T11:38:00.720 に答える
1
$('#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>
于 2019-04-11T09:27:43.943 に答える