在克隆期间更改内部元素id

Jee*_*ppp 11 javascript jquery clone twitter-bootstrap

我正在按钮单击时修复DIV元素,我可以更改我正在克隆的DIV元素的ID值.但是有可能改变内部元素的id.

在下面的代码我改变了#selection克隆时的ID ,我需要动态更改id #select.

<div id="selections">
  <div class="input-group" id="selection">
    <span class="input-group-addon">
    <i class="icon wb-menu" aria-hidden="true"></i>
     </span>
    <select class="show-tick" data-plugin="select2" id="select">
      <option>True</option>
      <option>False</option>
    </select>
  </div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
  Add new selection
</button>
Run Code Online (Sandbox Code Playgroud)

JS下面

$(function() {
  //on click
  $("body").on("click", ".btn-primary", function() {
    alert($(".input-group").length)
    var
    //get length of selections
      length = $(".input-group").length,
      //create new id
      newId = "selection-" + length++,
      //clone first element with new id
      clone = $("#selection").clone().attr("id", newId);
    //append clone on the end
    $("#selections").append(clone);
  });
});
Run Code Online (Sandbox Code Playgroud)

vij*_*ayP 17

是..它完全有可能如下:

var clone = $("#selection").clone();
clone.attr("id", newId);

clone.find("#select").attr("id","select-"+length);

//append clone on the end
$("#selections").append(clone); 
Run Code Online (Sandbox Code Playgroud)