我已经注意到关于该问题的stackoverflow上的其他线程,但是它们似乎都没有足够接近我的问题,因此我无法找到解决方案。
我的情况是我在jquery中创建了一个“待办事项”列表。通过将项目添加到列表中来动态创建项目。
当您将鼠标悬停在程序中的“待办事项”项上时,您可以选择编辑“待办事项”或将其从列表中删除。
$(document).ready(function(){
var itemCount=0;
$("#addButton").on('click',function(e){
e.preventDefault();
var toDoItem= $(".tempText").val();
$("#todoList").append('<li>'+toDoItem+'<a href="#" class="edit">'+ " Edit me " +'</a><a href="#" class="remove">'+" Remove Me "+'</a></li>');
$('li').addClass('toDoItem')
itemCount=itemCount+1;
$("#count").text(itemCount);
return(false);
/*$("#count").text=("li").length;*/
});
$("#clearButton").on('click',function(e){
e.preventDefault();
$("li").remove();
itemCount=0;
$("#count").text(itemCount);
return(false);
});
$("ul").on('click','li', function(){
$(this).remove( );
});
}); 当我单击“删除”链接或“编辑”链接时,两者都将删除该项目。我只希望“删除”照顾删除该项目。我已经阅读了有关事件委派的所有建议,但这些建议似乎并没有给我带来任何帮助。
无需注册处理程序,而是将其li
添加到remove link(.remove
)中,然后在处理程序中找到li
元素的祖先并将其删除。
$("ul").on('click', '.remove', function () {
$(this).closest('li').remove();
//or $(this).parent().remove(); since the `li` is the direct parent of the link
});
演示:小提琴
现在的问题是,您正在将处理程序绑定到该li
元素,因此对元素的任何单击li
(包括在任何降序元素中)都将触发该处理程序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句