Is there a way to clone elements using JQuery?

前端 未结 3 671
予麋鹿
予麋鹿 2020-12-21 08:24

Is there a way to clone HTML elements using JQuery?

However, I want to be able to assign the cloned elements new attributes \"id, name\". So if I had a textfield ele

相关标签:
3条回答
  • 2020-12-21 08:59

    Once you have a cloned element you can change it any way you want to

    Updated: Didn't notice that you wanted to change both name and id.

    $("#example").clone()
                 .attr({"id":"example2", "name":"example2"})
                 .html("new content")
                 .appendTo("#container");
    
    0 讨论(0)
  • 2020-12-21 09:03

    Here is sample of creating clone using jquery.

    Html code::

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div style="margin: 10px 10px 10px 0px" id="addNewDiv"> <table style="width: 100%" id="maintable" class="cloneTable">
        <tr><td><input type="text" name="text" id="text"/></td></tr>
      </table></div>
    <input type="button" value="Add New Div" onclick="addNewDiv();" style="background-color: #3E8DE1; color: white;" />
    

    Javascript code::

    var count=1;
    
    function addNewDiv(){
        var $clone = $(".cloneTable:first").clone(true);
            $clone.find(':text,:file').each(function() {
                $(this).attr('id',($(this).attr("id")+count));
                $(this).val('');
            });
             $clone.find("a").each(function() {
                  $(this).val('').attr('id', function(_, id) {
                    return count;
                  });
                });
             $clone.find("span").each(function() {
                 $(this).attr({
                    id: $(this).attr("id") + count
             });
            });
    
    
                  $clone.attr( 'id', function() { 
    
                      return this.id + count; })
    
             .appendTo('#addNewDiv');
        count=count+1;
      }
    

    Here is the link of fiddle of same example. Clone Fiddle

    0 讨论(0)
  • 2020-12-21 09:10

    documentation

    I use jQuery over $ so it works with other libraries. Here is an example on an input text field.

    jQuery('#example').clone().val('').attr('id', 'exmple2').attr('name', 'exmple2').insertAfter('#example');
    

    If you want to clone the event handlers as well, you have to use clone(true).

    0 讨论(0)
提交回复
热议问题