我的表单字段有一个模板,我需要这些字段能够重复多次。
将此视为示例案例:
<a href='#' id="add">Add</a><br /><br />
<div id="box">
<div id="template">
<input type="text" name="template"></input>
<br /><br />
</div>
</div>
脚本:
var template = document.querySelector('#template');
var index = 1;
$('#template').remove();
$('body').on('click', '#add', function(e) {
e.preventDefault();
$('#box').append(template);
var newInput = $('#box').html().replace(/template/g, 'input-'+index);
$('#box').html(newInput);
index++;
});
http://jsfiddle.net/bedex78/hkk7rx74/7/
为什么每当我在字段中输入一些值时,添加新值时该值就会消失(即单击“添加”按钮后)?
最佳答案
使用 $('#box').html(newInput);
时,您将替换所有 HTML - 包括所有输入和值。使用clone
的组合来复制模板,并使用append
添加到框中而不替换其内容:
$('body').on('click', '#add', function(e) {
e.preventDefault();
var wrapper = $("<div>");
wrapper.append($(template).clone());
var newInput = wrapper.html().replace(/template/g, 'input-'+index);
$('#box').append(newInput);
index++;
});
注意:我在这里使用clone
的原因是为了让你可以正确地修改新的盒子。您不必使用 html().replace
,但可以使用 DOM 操作,例如wrapper.find("#template")
关于jquery - 重复时输入会失去值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30500905/