我做的按钮点击一个DIV元素的副本,我能够改变我克隆DIV元素的ID的价值。但是,它可能改变内部元素的ID。
在下面的代码我改变#selection
的标识,而克隆的,我需要动态改变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>
下面的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);
});
});
是的..其完全可能如下:
var clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","select-"+length);
//append clone on the end
$("#selections").append(clone);
您需要手动更改所有儿童的ID。
要么改变它只有一个这样的:
//clone first element with new id
clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","whateverID");
或者使用类似的东西,改变所有的孩子:jQuery changing the id attribute of all the children
使用类.show-tick
和.children()
方法来定位的元素:
clone.children('.show-tick').attr('id', 'select-' + length);
$(function() {
//on click
$(".btn-primary").on("click", 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);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>