开发者

remove elements javascript jquery

Im trying to remove a row. But i can't figure it out really. First of all I've got a button that'll add a new row, that works. But I want to give the user the possibili开发者_如何学运维ty to remove the just added row. The row has an 'div' inside what acts as an deletebutton. But the deletebutton doesn't work?

I'm I missing something?

Greet,

Juki

function addrow() {
$("#container").append("<div id=\"row_added\"><div class=\"deletebutton\" id=\"delbuttonnumber\"></div><div id=\"addedcolor\" class=\"colorcube\"></div></div>");
}

// deleterow the row
$(".deletebutton").click(function() {
    rowclrid = "#" + $(this).parent().attr("id");
    $(rowclrid).remove();
});


My guess is that you have assigned the click handler before adding the new content, so the handler is not attached to this particular element. You can use .delegate() to listen for events on all elements below a particular parent element, whether or not they already exist:

$('#container').delegate('.deletebutton', 'click', function(){
    $(this).parent().remove();
});

This listens for all click events that happen inside the element #container using a feature of the DOM called event bubbling, then checks to see if they happened on a .deletebutton element, and, if so, calls the handler.

Note also the simplified code inside the handler.


I think what you need to do is use the live method. This will add the events for any new item that is added to the DOM, not just the ones that exist when you set the click handler.

// deleterow the row
$(".deletebutton").live('click', function() {
    $(this).parent().remove();
});

You also don't need to get the row by getting the ID - it's simpler in the way above.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜