这是JsFiddle
我有一个按钮,单击该按钮将添加新的标题,文本框和链接。
但是,当我单击删除链接时。它会删除所有添加的新项目。
HTML:
<div id='main'>
Top of Boby
<div id='main_1'>
<div>
<h3> Item</h3>
<input type="text" />
</div>
</div>
</div>
JS:
$(function() {
$('.AddItem').click(function() {
$('div#main_1').append("<div><h3>Item</h3><input type='text' class='remove_skill'/><a href=''>Remove</a</div>");
});
})
$(function() {
$('.remove_skill').click(function() {
$(this).remove();
});
})
最佳答案
您发布的代码的问题在于,调用$('.remove_skill').click
时不存在任何链接,因此无法向其添加事件侦听器。
我建议采取循序渐进的方法。创建,添加行为,追加到文档。
$('.AddItem').click(function () {
var new_element = $('<div class="item"><h3>Item</h3><input type="text"/><a class="remove" href="#">Remove</a></div>');
new_element.find(".remove").click(remove_item);
$('div#main_1').append(new_element);
});
function remove_item() {
$(this).closest(".item").remove();
return false;
}
对于JavaScript处理的链接,建议使用
<a href="#">
。使用闭包的替代解决方案:
$('.AddItem').click(function () {
var new_element = $("<div class="item"><h3>Item</h3><input type='text'/><a class="remove" href="#">Remove</a</div>");
new_element.find(".remove").click(function() {
new_element.remove();
});
$('div#main_1').append(new_element);
});