我写了一个简单的函数来克隆一个字段:
在线演示:http://jsfiddle.net/5yVPg/
<div id="main">
<a id="add-input" href="#">+ add</a>
<p class="child">
<input type="text" name="user[]" />
<a href="#" class="icon-delete">delete</a>
</p>
</div>
$(document).ready(function () {
$('#add-input').click(function () {
var newField = $('.child').clone()
newField.toggle().attr('class', '')
registerRemoveHandlers(newField, '.icon-delete')
$(this).parent().append(newField)
return false
})
function registerRemoveHandlers(el, class) {
$(el).find(class).click(function () {
$(this).parents('p:first').remove()
return false
})
}
})
我想从第一个输入中删除删除图标,我试过:
$('p.child .icon-delete:first').css('display','none')
但是没有为所有输入显示删除图标。
PS:如果我可以优化上面的代码,我会很高兴:)
答案 0 :(得分:2)
请看一下这个:
// Keep a single clone of the original
var clonedField = $('.child').clone(),
main = $('#main');
// Add in the delete <a> to the cloned field
$('<a>', {
text: 'delete',
class: 'icon-delete',
href: '#',
click: function(){
$(this).parent().remove();
return false;
}
}).appendTo(clonedField);
// Clone the cloned original and append it back to the list
$('#add-input').click(function() {
main.append(clonedField.clone());
return false;
});
代码更简单,更容易理解,然后你有什么,并且应该按照你的预期工作。
在jsfiddle上查看:http://jsfiddle.net/5ZFh6/
答案 1 :(得分:2)
$(function() {
$('#add-input').click(function() {
$('<p><input type="text" name="user[]" /> ' +
'<a href="#" class="icon-delete">delete</a></p>').appendTo('#main');
});
// just for sake...
$('.icon-delete').live('click',
function() {
$(this).parent().fadeOut(500,
function() {
$(this).remove();
});
});
});
<强>陷阱:
答案 2 :(得分:1)
我认为这样可以解决问题....... $('p.child .icon-delete:first').css('display','none')
隐藏了.icon-delete
的所有p.child
。在您的情况下,所有p.child
都是.icon-delete
$('p.child:first .icon-delete').css('display','none')
答案 3 :(得分:0)
$('#add-input').bind('click',function ()
{
var newField = $('.child').clone();
newField.toggle().attr('class', '');
registerRemoveHandlers(newField, '.icon-delete');
$('p.child:last').after(newField); //append after not cloned child
newField.parent().children('p').find('a').show(); //show all 'delete' label
newField.prev().find('a').hide(); //hide label from the first child which is right the one before our clone
return false;
});