Comment jQuery clone() et changer d'id?

J'ai besoin de cloner l'id, puis ajouter un nombre après elle comme id1, id2, etc. Chaque fois que vous frappez clone vous mettez le clone après le dernier numéro de l'id.

$("button").click(function() {
    $("#id").clone().after("#id");
}); 
105
demandé sur informatik01 2012-04-12 19:08:19

3 réponses

$('#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>
167
répondu Roko C. Buljan 2017-09-23 12:16:45

Mise À Jour: commeRoko C. Bulijan l'a souligné.. vous avez besoin d'utiliser .insertAfter pour l'insérer après la div sélectionnée. Voir aussi code mis à jour si vous voulez qu'il soit ajouté à la fin au lieu de commencer lorsqu'il est cloné plusieurs fois. DÉMO

Code:

   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
   }); 

Essayez,

$("#id").clone().attr('id', 'id1').after("#id");

Si vous voulez un compteur automatique, alors voir ci-dessous,

   var cloneCount = 1;
   $("button").click(function(){
      $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
   }); 
38
répondu Selvakumar Arumugam 2017-05-23 10:31:14

J'ai créé une solution généralisée. La fonction ci-dessous va changer les id et les noms de l'objet cloné. Dans la plupart des cas, vous aurez besoin du numéro de ligne, ajoutez simplement l'attribut "data-row-id" à l'objet.

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;
}
2
répondu Piyush Balapure 2016-09-08 11:38:00