简体   繁体   中英

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. 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 :

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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