开发者

Removing elements after DOM is ready

I have a few fields that a user can fill in (e.g., name, number, address), then they can click "Add" which creates a div that displays the information they just entered with a "Remove" button (a href) for each entry. The problem I'm having is that once the DOM is ready, the remove buttons do not work. I've hardcoded a remove butto开发者_StackOverflow中文版n that removes the 3rd div (3rd is arbitrary), and that works, but not the ones that are generated after the page is loaded. My question is how can I have the remove buttons work after the DOM is ready?

Here is the remove function (id is passed in, so it knows which div to remove):

function remove(id) {
    $("div.reviewSub"+id).remove();
}

And here is the handler to call the function:

$(".remove").click(function(event) {remove(event.target.id);});

The way I display the data after it has been retrieved is with .append():

$(".reviewSub"+num).append("<a href=\"#\" class=\"remove\" id=\"" + num + "\">Remove</a>");


You can use the live method in jQuery.

$('.remove').live('click', function(event){
    remove(event.target.id); 
});

I suspect that you have the code $(".remove").click(function(event) {remove(event.target.id);}); before you are appending the DOM. As a result, jQuery has not been able to bind the click event to the element as the element doesnt exist yet.

More documentation here http://api.jquery.com/live/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜