【问题标题】:How to clone and change id?如何克隆和更改ID?
【发布时间】:2012-04-24 23:10:22
【问题描述】:

我需要克隆 id,然后在其后添加一个数字,如 id1id2 等。每次点击克隆时,都会将克隆放在最新的 id 数字之后。

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

【问题讨论】:

    标签: javascript jquery clone


    【解决方案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>
    
    <button id="cloneDiv">CLICK TO CLONE</button> 
    
    <div id="klon1">klon1</div>
    <div id="klon2">klon2</div>

    加扰元素,检索最高ID

    假设您有许多 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>

    【讨论】:

    • +1 for Working demo :) 感谢您查看我的答案。我更新了帖子还添加了一个工作演示jsfiddle.net/HGtmR/4
    • 是否也可以在 div 内设置一个按钮来移除当前 id 的 div?
    • @user1324780 是的,这是可能的,但您应该将其作为一个新问题发布。无论如何,线索是找到 .closest(div[id^=id]).remove 那个 div。
    • 完全符合我的需要。它最有可能为我节省了数小时的开发时间!谢谢
    • 如何与 $(this) 一起使用??这是行不通的 $(this).('div[id^="picker-time-start"]');
    【解决方案2】:

    更新:正如Roko C.Bulijan 指出的那样.. 您需要使用 .insertAfter 将其插入到选定的 div 之后。如果您希望在多次克隆时将其附加到末尾而不是开头,请参阅更新的代码。 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");
       }); 
    

    【讨论】:

    • 您错过了在代码中使用'id'+ ++ id 的绝佳机会。
    • @RokoC.Buljan 你是对的,但问题是如何更改克隆元素的属性,所以我没有注意到.after。查看更新的答案。
    • :) +1 将其四舍五入为 5 ! ;) 很好地使用 [id^=id]:last 恭喜。
    • 这也可以应用于名称吗?
    【解决方案3】:

    这是对我来说最简单的解决方案。

    $('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
    

    【讨论】:

      【解决方案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>

      【讨论】:

        【解决方案5】:

        我创建了一个通用解决方案。下面的函数将更改克隆对象的 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;
        }
        

        【讨论】:

          【解决方案6】:
          $('#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>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-21
            • 2016-01-30
            • 2011-08-12
            相关资源
            最近更新 更多