documentFragment.cloneNode(true) doesn't clone jQuery data

纵然是瞬间 提交于 2019-12-24 10:48:07

问题


I have a documentFragment with several child nodes containing some .data() added like so:


myDocumentFragment = document.createDocumentFragment();
for(...) {
  myDocumentFragment.appendChild(
    $('<a></a>').addClass('button')
      .attr('href', 'javascript:void(0)')
      .html('click me')
      .data('rowData', { 'id': 103, 'test': 'testy' })
      .get(0)
  );
}

When I try to append the documentFragment to a div on the page:

$('#div').append( myDocumentFragment );

I can access the data just fine:

alert( $('#div a:first').data('rowData').id ); // alerts '103'

But if I clone the node with cloneNode(true), I can't access the node's data. :(

$('#div').append( myDocumentFragment.cloneNode(true) );
...
alert( $('#div a:first').data('rowData').id ); // alerts undefined

Has anyone else done this or know of a workaround? I guess I could store the row's data in jQuery.data('#some_random_parent_div', 'rows', [array of ids]), but that kinda defeats the purpose of making the data immediately/easily available to each row.

I've also read that jQuery uses documentFragments, but I'm not sure exactly how, or in what methods. Does anyone have any more details there?

Edit re: .clone(true)


$(globalObj).data('fragment', { frag: $(mydocumentFragment).clone(true) });

$(myDocumentFragment).clone(true).appendTo('#div');

alert( $('#div a:first').data('rowData').id ); // undefined

回答1:


You're creating a jQuery object when you do $('a'), but you're leaving it behind when you use get(0) and use appendChild to append it to your fragment. So if you use the native .cloneNode(true) on your fragment, jQuery is not aware of it, and therefore is not managing the data for you.

As long as you're using jQuery for most of what you're doing, I'd say ditch the documentFragment, and just stuff your a elements into a jQuery object, and clone() that.

I don't think you're gaining anything by using a fragment in this case.



来源:https://stackoverflow.com/questions/2831414/documentfragment-clonenodetrue-doesnt-clone-jquery-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!