输入在复制时失去价值
Input loses value when duplicated
我有一个表单域模板,我需要这些域能够被多次复制。
将此视为示例:
<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/
为什么每当我 在字段中输入一些值 时, 值在添加新值 后消失(即点击'ADD' 按钮)?
您在使用 $('#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")
这是因为输入的值没有存储在 html 本身。
您的问题的解决方案是:
$('body').on('click', '#add', function(e) {
e.preventDefault();
var newInput = $(template).html().replace(/template/g, 'input-'+index);
$('#box').append(newInput);
index++;
});
jsfiddle : http://jsfiddle.net/hkk7rx74/8/
我有一个表单域模板,我需要这些域能够被多次复制。
将此视为示例:
<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/
为什么每当我 在字段中输入一些值 时, 值在添加新值 后消失(即点击'ADD' 按钮)?
您在使用 $('#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")
这是因为输入的值没有存储在 html 本身。
您的问题的解决方案是:
$('body').on('click', '#add', function(e) {
e.preventDefault();
var newInput = $(template).html().replace(/template/g, 'input-'+index);
$('#box').append(newInput);
index++;
});
jsfiddle : http://jsfiddle.net/hkk7rx74/8/