不能删除我添加的div

时间:2016-01-27 13:42:01

标签: jquery

我使用以下代码在页面中添加了一些元素,效果很好:

$("body").on("click", "#buttonadd", function(){
    var vriend = "<div id='friends'><h4>Jaap Smit</h4><div class='unfollow'><a href='#' class='removefriend'>Delete friend</a></div></div>";
    $(this).parent().siblings(".currentfriends").append(vriend);
});

但是当我尝试使用以下代码删除它时,什么都不会发生......

$("body").on("click", "a.removefriend", function(){
    $(this).closest('.vriend').remove();
});   

现在已经尝试了很长时间,但我不知道如何解决它。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

班级vriend没有任何内容。您可能想要删除#friends

$("body").on("click", "a.removefriend", function(){
    $(this).closest('#friends').remove();
});

答案 1 :(得分:0)

您正在尝试使用类&#34; vriend&#34;删除对象。使用$(".vriend"),而不是定义的变量。因为(至少在显示的代码中)没有适合的目标没有任何事情发生。  请改为$(this).closest(vriend).remove();