jQuery删除功能真的删除Dom元素吗? [英] Does jQuery remove function really remove Dom elements?

查看:126
本文介绍了jQuery删除功能真的删除Dom元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的想知道jQuery 删除 功能是否真的删除元素来自DOM。

首先,我看了这里,但答案不能令人信服。

当我注意到我仍然能够操纵我已经调用remove功能的元素时遇到这个问题。

I am really wondering if jQuery remove function really remove elements from DOM.
First, I looked here but the answers are not convincing.
I encountered this problem when I noticed I am still able to manipulate elements on which I have called remove function.

我的代码:

<div id="container">
    <div id="div">
        This is a div
    </div>
</div>

var div = $('#div');
$('#div').remove();
$('#container').append(div);

注意:我的问题不是如何解决? ,但我想了解这里发生了什么!


实际上,此代码不会从dom中删除#div,但如果我有任何数据设置为#div,它将丢失。现在我很困惑删除函数的行为。有人可以解释一下吗
演示



我是相信div变量不仅仅是dom元素的克隆,是一个引用,因为当我操纵div变量时,(如 div.html('something') )DOM内的 div 更新。

或者我错了?

Note: My question is not how to solve this? but I want to understand what's going on here!

Actually, this code doesn't remove the #div from the dom, but if I have any data set to the #div, it will be lost. I am pretty confused now about the behaviour of remove function. Can anyone explain this please? DEMO

I am convinced that div variable is not just a clone of the dom element, is a reference to it, because when I manipulate the div variable, (like div.html('something')) the div within the DOM get updated.
Or am I wrong?

推荐答案

remove()确实从DOM中删除了元素。

remove() does indeed remove the element from the DOM.

但是,在您的示例中,元素已被缓存在内存中,因为您将它分配给 div 变量。因此,您仍然可以使用它,并再次添加它,它仍将包含原始的所有事件。

However in your example, the element has been cached in memory because you assigned it to the div variable. Therefore you can still use it, and append it again, and it will still contain all the events the original did.


如果你说的话是对的,为什么我放弃绑定到div的数据?

If what you say is right, why I loose the data bound to the div so?

如果你检查 source for remove(),你会看到它调用内部 cleanData 函数,它删除事件并清除元素的数据缓存。这就是为什么你丢失了信息。

If you check the source for remove() you'll see that it calls the internal cleanData function which removes the events and clears the data cache for the element. This is why you lose the information.

如果要从DOM中删除元素,但保留元素,请使用 detach()

If you want to remove the element from the DOM, but keep the elements, use detach() instead.

这是一个小提琴来显示区别: http://jsfiddle.net/2VbmX/

Here's a fiddle to show the difference: http://jsfiddle.net/2VbmX/

这篇关于jQuery删除功能真的删除Dom元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆