http://jsbin.com/jejujizi/1/edit
$(document).ready(function() {
$(".cs").on('click', function() {
$(".newclones").append("<div class='container'>").append($(".toclone .clone").clone()).append("<button class='rem'>Delete</button>");
$(".rem").on('click', function() {
$(this).prev().remove();
$(this).remove();
});
});
});
克隆一个 select 元素不是问题,克隆具有更改值的 select 元素才是问题。 (正如你在我的 fiddle 中看到的那样)
为什么不克隆更改后的值,如何解决?
最佳答案
根据 clone()
docs :
For performance reasons, the dynamic state of certain form elements (e.g., user data typed into
textarea
and user selections made to aselect
) is not copied to the cloned elements.
相反,您只需要在克隆元素后自己复制值:
$(document).ready(function() {
$(".cs").on('click', function() {
var toClone = $('.toclone .clone');
var toCloneClone = toClone.clone().val(toClone.val());
$(".newclones").append("<div class='container'>").append(toCloneClone).append("<button class='rem'>Delete</button>");
$(".rem").on('click', function() {
$(this).prev().remove();
$(this).remove();
});
});
});
关于javascript - 克隆具有选定值的选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24840650/