javascript - Dont understand why .remove() not working -
this question has answer here:
hi learning jquery , not understand why fucntion not work. when click button should remove div not.
the remove function
$(".editbutton").click(function () { $(".editbutton").remove(); });
function creates div
var formatpost = function (d) { var s = ''; s = '<div class="post" data-id="' + d.id + '"><h2 class="postheading">' + d.title + '</h2>'; s += d.body; s += '<p> posted on: ' + d.date + '</p>'; s += '<div class="btn editbutton">edit post</div>' s += '</div>' return s; };
currently using direct binding, works when element exist on page @ time code makes event binding call.
you need use event delegation using .on() delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)
use,
if want remove button
$(document).on('click', '.editbutton', function () { $(this).remove(); });
if want remove complete post, first, need execute action in current element context use this
. use closest()
find post
parent , use .remove()
$(document).on('click', '.editbutton', function () { $(this).closest('.post').remove(); });
Comments
Post a Comment