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. After remove(), the data is gone.
I would know how to work around this... but it seems odd to me - is this expected behavior?
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. After remove(), the data is gone.
I would know how to work around this... but it seems odd to me - is this expected behavior?
Share Improve this question edited Dec 24, 2015 at 20:44 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 4, 2014 at 14:35 WolfgangWolfgang 2,3381 gold badge27 silver badges28 bronze badges 3- 2 of course, you removed the element from the DOM entirely. the data associated with it would naturally get removed. if you want to retain the data, just hide the element instead of outright remove it. – PlantTheIdea Commented Aug 4, 2014 at 14:36
-
3
Yes, this is by design. Use
detach()
instead ofremove()
if you intend to re-append the element and want to keep its associated data around in the meantime. (Note that in your specific case, you do not even have to remove the element -- just callappend()
, it will move the element under its new container without cloning it). – Frédéric Hamidi Commented Aug 4, 2014 at 14:36 - 2 Thank you very much Frédéric, this was the answer - with .detach() and then .appendTo() the data does not get lost. With only '.appendTo()' (without preceeding '.remove()' the data still is lost. But '.detach().appendTo()' works :) Thanks again! – Wolfgang Commented Aug 4, 2014 at 15:57
2 Answers
Reset to default 4I think, so, judging from the Jquery Documentation:
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.
Ergo, even though you can still reference it, because the DOM element has been removed, the data associated with it has been removed.
You can use .detach() according to JQuery:
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.
var div = $("div").detach();
$(div).appendTo("body");
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745609879a4635886.html
评论列表(0条)