从DOM中删除元素并将它们添加到它们所在的位置 [英] Remove Elements From The DOM And Add Them Back In Where They Were

查看:128
本文介绍了从DOM中删除元素并将它们添加到它们所在的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模态窗口。我想要发生的是当模态打开时从页面中删除某些元素,并将它们添加回模态关闭后的正确位置。我不想做display:none,因为只隐藏它们,我需要将它们实际从页面中删除。所以我有一些jQuery删除并在计时器之后将它们添加回来进行测试...

I've got a modal window. What I want to happen is to remove certain elements from the page when the modal opens and add them back in right where they were after the modal closes. I don't want to do display:none, because that only hides them, I need them to actually be removed from the page. So I have a bit of jQuery to remove and add them back in after a timer just for testing...

更新:通过对代码的这些添加,它现在抓住元素,然后在相同的元素后添加回来。问题是,如果该元素也被删除了怎么办?然后它不会重新加入!另外,javascript事件处理程序不会丢失吗?我正在开发一个插件,所以它应该尽可能少地干扰网站,但是3D元素在Safari中有一个bug是不可能的。

关于如何在不干扰人们网站的情况下暂时删除3D元素的任何想法?

$3delements = $('*').filter(function(){return $(this).css('-webkit-transform-style') == 'preserve-3d'});
$3delementsposition = $3delements.prev()

//On modal open
$3delements.remove();

//On modal close
$3delementsposition.after($3delements);

问题是,这需要我在DOM中指定一个位置让他们重新进入。我希望这些元素能够回归到原来的位置。如何确保元素不会将.remove上的信息更改/移动/丢失到.append。

The problem is that this requires I specify a certain place in the DOM for them to come back in. I'd like the elements to come back in where they were. How can I make sure the elements don't change/move/lost information on the .remove to the .append.

推荐答案


  1. 使用 .detach() .append()删除并重新附加元素,它将维护您的所有事件和数据。

  1. Use .detach() and .append() to remove and reattach elements, it will maintain all your events and data.

如果按照与删除元素相反的顺序添加元素,它们应该全部回归到位

If you add elements back in the reverse order that you removed them, they should all fall back in place






未经测试的代码


untested code

var elems3d = $(...);
var elemsRemoved = [];

// removing
elems3d.each(function(i,o) {
   var elem = $(o);
   elemsRemoved.push({
       loc: elem.prev(),
       obj: elem.detach()
   });
});

// adding back
while (elemsRemoved.length) {
   var elem = elemsRemoved.pop();
   elem.loc.after(elem.obj);
}

这篇关于从DOM中删除元素并将它们添加到它们所在的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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