克隆其中包含文本的字段也会克隆文本吗? [英] Cloning a field with text in it clones text as well?
问题描述
我有一段代码可以克隆三个字段,但是当它克隆这三个字段时,它也可以克隆其中输入的文本,是否有一种方法可以在克隆时清除字段中的内容? /p>
I have a piece of code that clones three fields, but when it clones the three fields, it also clones the text entered inside of it, is there a way to clear the content inside of the field when it is cloned?
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedSection').length;
var newNum = new Number(num + 1);
var newSection = $('#clonedSection' + num).clone().attr('id', 'clonedSection' + newNum);
newSection.children(':first').children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newSection.children(':nth-child(2)').children(':first').attr('id', 'age' + newNum).attr('name', 'age' + newNum);
newSection.children(':nth-child(3)').children(':first').attr('id', 'school' + newNum).attr('name', 'school' + newNum);
$('.clonedSection').last().append(newSection);
$('.clonedSection').last().val(ping);
$('#btnDel').attr('disabled','');
if (newNum == 2)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedSection').length; // how many "duplicatable" input fields we currently have
$('#clonedSection' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
先谢谢!
推荐答案
您在做什么 .clone()
您可以找到/清除字段,如下所示:
Where you're doing .clone()
you can find/clear the fields, like this:
.clone().find(':text, textarea').val('').end()
如果您没有<textarea>
元素,那么可以省去一点,这是执行 .find()
获取文本元素, .val()
清除它们并 .end()
之后将链返回到使用coned元素,而不是我们正在寻找的文本元素
If you don't have <textarea>
elements you an leave out that bit, what this does is perform a .find()
to get the text elements, .val()
to clear them and .end()
to return the chain afterwards to using the coned element, not the text elements we were looking for.
或者,如果您输入以下内容,则作为替代:
Or, alternative, if these lines are your inputs:
newSection.children(....)
只需在每个代码的末尾添加.val('')
,例如第一个可能看起来像这样:
just add a .val('')
on the end of each , for example the first could look like this:
newSection.find('> :first > :first').attr({'id': 'name' + newNum, 'name': 'name' + newNum }).val('');
这篇关于克隆其中包含文本的字段也会克隆文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!