克隆时用jQuery删除第一课 [英] remove first class with jQuery while cloning
本文介绍了克隆时用jQuery删除第一课的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个简单的函数来克隆一个字段:
在线演示: http://jsfiddle.net/5yVPg/
HTML:
< div id =main>
< a id =add-inputhref =#> + add< / a>
< p class =child>
< input type =textname =user []/>
< a href =#class =icon-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)
返回false
})
函数registerRemoveHandlers(el,class){
$(el).find(class).click(function(){
$(this).parents('p:first')。remove()
return false
})
}
})
我想从第一个输入中删除删除图标,我试过了:
$('p.child .icon-delete:first')。css('display','none')
但是不会显示所有输入的删除图标。
PS:如果我可以优化上面的代码我会很高兴:)
解决方案
请看看这个:
//保留原始
的一个克隆var clonedField = $('。child')。clone(),
main = $('#main');
//添加删除< a>到克隆的字段
$('< a>',{
text:'delete',
class:'icon-delete',
href:'#',
click:function(){
$(this).parent()。remove();
return false;
}
})。appendTo(clonedField) ;
//克隆克隆的原始文件并将其追加回列表
$('#add-input')。click(function(){
main.append(clonedField .clone());
返回false;
});
代码更简单,更容易理解,那么您在那里得到了什么,并且应该按照您的预期工作。
在jsfiddle上查看: http://jsfiddle.net/ 5ZFh6 /
I write a simple function to clone a field:
Online Demo: 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
})
}
})
I want to remove the delete icon from the first input, I tried :
$('p.child .icon-delete:first').css('display','none')
But the delete icon being not displayed for all input.
PS: If I could optimize the codes above I'll be happy :)
解决方案
Have a look at this instead:
// 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;
});
The code is simpler and easier to understand then what you have there, and should work as you expect it.
See it on jsfiddle: http://jsfiddle.net/5ZFh6/
这篇关于克隆时用jQuery删除第一课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文