临时删除并稍后重新插入DOM元素? [英] temporarily removing and later reinserting a DOM element?

查看:116
本文介绍了临时删除并稍后重新插入DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些jquery魔术可以让我执行以下操作:

[0-定义HTML中的某些元素(例如,未选中复选框)]

1-通过使用.attr()设置其DOM属性之一来更新其DOM元素(例如,通过使用.attr('checked',true)设置其"checked"属性)

2-暂时从DOM中删除该元素

3-将原始元素重新插入DOM,同时保留其所有属性(即,使其像在第1步结束时一样进行检查-与最初在HTML中定义时不一样)

之所以我有兴趣从DOM中删除这些元素(而不是隐藏它们),是因为我注意到它似乎在很大程度上改善了性能.我的页面具有三个不同的状态",并且在任何给定状态下仅需要DOM元素总数的三分之一. [我希望将其作为具有不同状态的单个页面保留,而不是将其分成三个单独的页面.]

直到现在,我一直通过将

的值存储在var中来将元素删除并重新插入DOM中.

$("#myElement").html()

,然后将其删除,但是现在我注意到,将HTML重新插入DOM后,[在步骤1]中所做的更改已被撤消".

是否有一种方法-以保留其所有属性以供以后重新插入的方式从DOM中临时删除不需要的内容?

感谢您的见识,

lara

解决方案

您可以使用 方法:

var els = $('.els'), saved = els.clone (true);
els.remove ();
// .... do other stuff
saved.appendTo ($('.wherever-you-want-to'));

尽管如此,最好显示&隐藏它们(例如,通过display: none),而不是操作DOM,因为它非常昂贵.如果需要,请使用DOM插入&删除(如上所述),而不是.html (),它每次都会根据给定的字符串重新创建一个节点.

Is there some jquery magic that will let me do the following:

[0- define some element in HTML (eg, a unchecked checkbox)]

1- update its DOM element by setting one of its attributes using .attr() (eg, by setting its "checked" attribute using .attr('checked', true) )

2- temporarily remove that element from the DOM

3- reinsert the original element into the DOM, while preserving all its properties (ie, so that it is checked as it was at the end of step 1-- NOT like it was when initially defined in the HTML)

The reason why I am interested in removing these elements from the DOM (rather than hiding them) is that I have noticed that it seems to improve performance a good bit. My page has three different "states" and only a third of the total number of DOM elements is needed in any given state. [I wish to keep it as a single page with different states rather than breaking it into three separate pages.]

Until now I had been removing and reinserting elements into the DOM by storing in a var the value of

$("#myElement").html()

and then removing it, but now I noticed that upon reinsertion of that HTML into the DOM the changes made [in step 1] had been "undone".

Is there a way to do this -- to temporarily remove unneeded stuff from the DOM in a way that preserves all its properties for later reinsertion?

thanks for any insight,

lara

解决方案

You may use the clone method:

var els = $('.els'), saved = els.clone (true);
els.remove ();
// .... do other stuff
saved.appendTo ($('.wherever-you-want-to'));

That said, though, it's better to show & hide them (via display: none, for example), than to manipulate the DOM as it's very expensive. If you have to, use DOM insertion & removal (as above), rather than .html (), which recreated a node from the given string every time.

这篇关于临时删除并稍后重新插入DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆