gpt4 book ai didi

javascript - 克隆时使用 jQuery 删除第一类

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:12 25 4
gpt4 key购买 nike

我写了一个简单的函数来克隆一个字段:

在线演示:http://jsfiddle.net/5yVPg/

HTML:

<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>

JS:

$(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:如果我能优化上面的代码,我会很高兴:)

最佳答案

看看这个:

// 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/

关于javascript - 克隆时使用 jQuery 删除第一类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4884362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com