2010-08-12 106 views
0

我有一段代碼可以克隆三個字段,但是當它克隆三個字段時,它也克隆了輸入到其中的文本,有沒有辦法在克隆時清除字段內的內容?克隆其中的文本字段以及克隆文本?

$(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'); 
}); 

Thanx提前!

回答

1

如果你正在做.clone()你可以找到/清除場,像這樣:

.clone().find(':text, textarea').val('').end() 

如果你沒有<textarea>元素,你的離開了這一點,這是什麼做的是執行.find()得到文本元素,.val()清除它們,然後.end()將鏈返回到使用coned元素,而不是我們要查找的文本元素。

或者替代,這些線路是否您的輸入:

newSection.children(....) 

只是在每年年底增加.val(''),例如第一個看起來是這樣的:

newSection.find('> :first > :first').attr({'id': 'name' + newNum, 'name': 'name' + newNum }).val(''); 
+0

Thanx,這工作完美! – Odyss3us 2010-08-12 12:44:10

1

value屬性正好被設置爲使用.attr("value", "")空字符串(我假設你是在談論一個<input type="text" />):

newSection.children(':first').children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum).attr('value', ''); 
1

你可以清除輸入的元素是這樣的:

newSection.find(':input').val('');