documentFragment.cloneNode(true)不克隆jQuery数据 [英] documentFragment.cloneNode(true) doesn't clone jQuery data
问题描述
我有一个documentFragment,其中有几个子节点,其中包含一些.data(),如下所示:
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)
);
}
当我尝试将documentFragment附加到页面上的div时:
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'
但是,如果我使用cloneNode(true)克隆节点,则无法访问该节点的数据. :(
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
是否还有其他人这样做或知道解决方法?我想我可以将行的数据存储在jQuery.data('#some_random_parent_div', 'rows', [array of ids])
中,但这有点违反了使数据可立即/轻松地用于每一行的目的.
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.
我还阅读了jQuery使用documentFragments的信息,但是我不确定确切如何使用或使用哪种方法.有人在那里有更多细节吗?
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?
编辑以下内容:.clone(true)
$(globalObj).data('fragment', { frag: $(mydocumentFragment).clone(true) });
$(myDocumentFragment).clone(true).appendTo('#div');
alert( $('#div a:first').data('rowData').id ); // undefined
推荐答案
您在执行$('a')
时正在创建jQuery对象,但是当您使用get(0)
并使用appendChild
来创建jQuery对象时将其附加到您的片段.因此,如果您在片段上使用本机.cloneNode(true)
,则jQuery不会意识到它,因此不会为您管理数据.
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.
只要您使用jQuery来完成大部分工作,我都会说放弃documentFragment,然后将a
元素放入jQuery对象中,然后将clone()
填充进去.
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.
这篇关于documentFragment.cloneNode(true)不克隆jQuery数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!