简体   繁体   English

删除元素javascript jquery

[英]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 possibility to remove the just added row. 但我想给用户删除刚刚添加的行的可能性。 The row has an 'div' inside what acts as an deletebutton. 该行内部有一个“ div”,用作删除按钮。 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: 您可以使用.delegate()侦听特定父元素下的所有元素上的事件,无论它们是否已经存在:

$('#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. 这会使用DOM的名为事件冒泡的功能来监听元素#container中发生的所有单击事件,然后检查它们是否发生在.deletebutton元素上,如果是,则调用处理程序。

Note also the simplified code inside the handler. 还要注意处理程序中的简化代码。

I think what you need to do is use the live method. 我认为您需要做的是使用live方法。 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. 这将为添加到DOM的任何新项目添加事件,而不仅仅是设置click处理程序时存在的事件。

// 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. 您也不需要通过获取ID来获取行-上面的方法更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM