我正在尝试在我的 DOM 中查找并克隆一个元素。克隆后,我想清除元素值,然后将它们附加到容器底部。
出于某种原因,我似乎无法清除该值。目前,该行被附加但具有与第一行相同的值。我想克隆对象并省略值。
如何修复以下代码以克隆除值之外的所有内容?
// replaces the index of each element to the giving index. so Title[0][name] will become Title[index][name]...
window.getContent = function (html, index) {
return html.replace(/_\d+__/g, '_' + index + '__')
.replace(/\[\d+\]/g, '[' + index + ']');
}
$(function(){
$('#addRow').click(function(){
// find the first row inside #container
// clone it, find any input inside of it and set its value to empty string
var template = $('#container .row').first().clone().find(':input').val('').end();
// find the current count of the rows inside the container
var index = $('#container .row').length;
// replace the index inside the element name to the correct index
var content = getContent(template.prop('outerHTML'), index);
// append the new element on to the container
$('#container').append(content);
});
});
这是一个JS Fiddler使用上面的代码
最佳答案
尝试:
var template = $('#container .row').first().clone().find(':input').attr('value','').end();
应该为你做。
问题是 val
不会处理 default value
属性,这就是为什么需要 attr
的原因。
关于javascript - 如何使用 jQuery 重置克隆对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470367/