如何使用jquery克隆时获取元素的当前数据。在克隆时,它的副本只是元素中的默认数据。
这是代码
souRce.clone()
.prop('id', newName)
.html(function () {
return $(this).html().replace(RegExp(PrevID, 'g'), newName);
})
.appendTo(DestiNation);
答案 0 :(得分:1)
问题是,您使用原始html更改其内容,而不是使用克隆元素,原始html将使用原始html标记替换运行时内容
因此,不要更换整个html,只需更新id
和name
属性,例如
var counter = 1;
function clone() {
var souRce = $('.item').eq(0),
DestiNation = $('#ct'),
PrevID = 'item-' + counter,
newName = 'item-' + ++counter;
var regex = RegExp(PrevID, 'g');
souRce.clone()
.prop('id', newName)
.find('[id], [name]').each(function() {
if (this.id) {
this.id = this.id.replace(regex, newName);
}
if (this.name) {
this.name = this.name.replace(regex, newName);
}
}).end()
.appendTo(DestiNation);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ct">
<div class="item" id="item-1">
<input name="a" value="A" id="a-item-1" />
<input name="b" value="B" id="b-item-1" />
<input name="c-item-1" value="C" id="c-item-1" />
</div>
</div>
<button onclick="clone()">Clone</button>
&#13;