如何恢复已删除的元素到他原来的位置

jQuery可以复制并删除一个元素:
var $temp = $("#test").clone(true);
$("#test").remove();
这时$temp已经不在dom tree之中了,如果想把它加回到dom tree,可以$("body").append($temp);。但是如何能把这个$temp加到他原来的位置呢?难道只能提前记录他的父亲元素么?

回复
阅读 7.5k
2 个回答

决定这么做:
先记录每个元素的位置:

var $locations = [];
$(".auto-header").each(function() {
    var $this = $(this),
        offset = $this.offset();
    $locations.push($this.siblings().eq($this.index()));
});

删除并恢复元素:

$(".auto-header").each(function(i, e) {
    $te = $(this).clone(true);
    $(this).remove(); // remove
    // do something
    $locations[i].before($te); // restore
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏