删除元素,但保留所有数据和事件绑定

时间:2022-09-07 23:58:00

I have a container that could be injected in any specified container on the page (like a popup). Popup should have a button which deletes parent element. I tried using .remove() to delete parent element, however, it also removes popup and its events. I want it to remove popup (I still have the reference), however, I don't want .remove to unbind the events.

我有一个容器可以被注入到页面上的任何指定容器中(比如弹出窗口)。弹出窗口应该有一个删除父元素的按钮。我尝试使用.remove()来删除父元素,但是,它也会删除弹出窗口及其事件。我想要它删除弹出窗口(我仍然有引用),但是,我不想要.remove来解绑定事件。

So far, I got this:

到目前为止,我得到了这个:

var popup = $('#popup');

$('body > div').on('click', function () {
    popup.appendTo($(this));
});

popup.find('button').on('click', function () {
    $(this).closest('div:not(#popup)').remove();
});

http://jsfiddle.net/volter9/0zms29g1/

http://jsfiddle.net/volter9/0zms29g1/

Basically, is there a way to delete an element without removing its data or events?

基本上,是否有一种方法可以在不删除元素的数据或事件的情况下删除元素?

Thank you for attention!

感谢您的关注!

P.S.: I tried to append and hide popup in the body, but it's not what I need.

注:我试着在身体里添加和隐藏弹出窗口,但这不是我需要的。

1 个解决方案

#1


11  

You can use .detach()

您可以使用.detach()

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

detach()方法与.remove()方法相同,只是.detach()将所有jQuery数据与删除的元素关联起来。当删除的元素稍后被重新插入DOM时,该方法是有用的。

Also you can append the detach element to the DOM by using the return value:

还可以使用返回值将detach元素附加到DOM:

var div = $("div").detach();

$(div).appendTo("body");

#1


11  

You can use .detach()

您可以使用.detach()

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

detach()方法与.remove()方法相同,只是.detach()将所有jQuery数据与删除的元素关联起来。当删除的元素稍后被重新插入DOM时,该方法是有用的。

Also you can append the detach element to the DOM by using the return value:

还可以使用返回值将detach元素附加到DOM:

var div = $("div").detach();

$(div).appendTo("body");