开发者社区 问答 正文

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

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

展开
收起
杨冬芳 2016-06-15 10:44:52 2387 分享 版权
1 条回答
写回答
取消 提交回答
  • IT从业

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

    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
    });
    2019-07-17 19:38:52
    赞同 展开评论
问答分类:
问答地址: