[英]jquery .data lost after remove() and append()
Sorry, this seems like a stupid question... but is this actually expected behaviour? 对不起,这似乎是一个愚蠢的问题......但这实际上是预期的行为吗?
I store data on some element: 我在一些元素上存储数据:
$('#source-list li.active').data('relation-text', textEditor.value());
Later the element is moved from one list to another: 之后,元素从一个列表移动到另一个列表:
$('#source-list li.active').remove().appendTo('#target-list')
Right before 'remove()' 'data()' returns the expected value. 在'remove()之前''data()'返回预期值。 After remove(), the data is gone.
删除()后,数据消失了。
I would know how to work around this... but it seems odd to me - is this expected behavior? 我知道如何解决这个问题......但对我来说这似乎很奇怪 - 这是预期的行为吗?
I think, so, judging from the Jquery Documentation : 我想,从Jquery文档来看:
The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
.data()方法允许我们以一种不受循环引用安全的方式将任何类型的数据附加到DOM元素,从而避免内存泄漏。
Ergo, even though you can still reference it, because the DOM element has been removed, the data associated with it has been removed. 因此,即使您仍然可以引用它,因为DOM元素已被删除,与之关联的数据已被删除。
You can use .detach() according to JQuery: 你可以根据JQuery使用.detach():
The .detach() method is the same as .remove(), except that .detach() keeps >all jQuery data associated with the removed elements.
.detach()方法与.remove()相同,除了.detach()保持>所有与删除元素相关联的jQuery数据。 This method is >useful when removed elements are to be reinserted into the DOM at a later time.
当删除的元素稍后要重新插入DOM时,此方法很有用。
var div = $("div").detach();
$(div).appendTo("body");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.