我已经注意到了关于这个问题的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( );
});
}); 当我点击&#39;删除&#39;链接或编辑&#39;链接,两者都将删除该项目。我只想要&#39;删除&#39;照顾删除该项目。有什么建议 我已阅读有关活动授权的网页,但他们似乎并没有把我带到任何地方。
答案 0 :(得分:1)
不是将处理程序注册到li
,而是将其添加到删除链接(.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
});
演示:Fiddle
现在的问题是,您将处理程序绑定到li
元素,因此对li
元素(包括任何降序元素)的任何单击都将触发处理程序。