jQuery clone duplicate IDs

后端 未结 9 1779
醉梦人生
醉梦人生 2020-12-04 19:03

I have an HTML element with a large collection of unordered lists contained within it. I need to clone this element to place elsewhere on the page with different styles adde

相关标签:
9条回答
  • 2020-12-04 19:31

    Here is a solution with id.

    var clone = $("#MainConfig").clone();
    clone.find('[id]').each(function () { this.id = 'new_'+this.id });
    $('#smallConfig').append(clone);
    

    if you want dynamically set id, you can use counter instead of 'new_'.

    0 讨论(0)
  • 2020-12-04 19:32

    I believe this is the best way

    var $clone = $("#MainConfig").clone(false);
    $clone.removeAttr('id'); // remove id="MainConfig"
    $clone.find('[id]').removeAttr('id'); // remove all other id attributes
    $clone.appendTo($("#smallConfig")); // add to DOM.
    
    0 讨论(0)
  • 2020-12-04 19:33

    If you need a way to reference the list items after you've cloned them, you must use classes, not IDs. Change all id="..." to class="..."

    If you are dealing with legacy code or something and can't change the IDs to classes, you must remove the id attributes before appending.

    $("#MainConfig").clone(false).find("*").removeAttr("id").appendTo($("#smallConfig"));
    

    Just be aware that you don't have a way to reference individual items anymore.

    0 讨论(0)
  • 2020-12-04 19:41

    I use something like this: $("#details").clone().attr('id','details_clone').after("h1").show();

    0 讨论(0)
  • 2020-12-04 19:41

    FWIW, I used Dario's function, but needed to catch form labels as well.

    Add another if statement like this to do so:

    if(element.htmlFor){
    var matches = element.htmlFor.match(/(.+)_\d+/);
    if(matches && matches.length >= 2)            // Captures start at [1].
      element.htmlFor = matches[1] + "_" + cur_num;
    }
    
    0 讨论(0)
  • 2020-12-04 19:47

    If you will have several similar items on a page, it is best to use classes, not ids. That way you can apply styles to uls inside different container ids.

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