恢复使用parentNode.removeChild删除的项目



你知道我如何通过以下方式恢复用JavaScript删除的项目吗:

elem1.parentNode.removeChild(elem1);

MDN 文档中所述removeChild将返回对已删除子节点的引用。用法如下:

var oldChild = element.removeChild(child);
element.removeChild(child);

进一步:

删除的子节点仍存在于内存中,但不再是一部分 的 DOM。您可以稍后在代码中重用已删除的节点,通过 旧子对象引用。

如果在删除元素之前将元素存储在变量中,则无法撤消removeChild()调用。在没有赋值的情况下自行调用函数将完全将其从 DOM 内存中删除。

你可以通过这样做强制 JavaScript 将其存储在内存中以供以后使用/恢复:

var restoration_element = elem1.parentNode.removeChild(elem1);

将后一种语法与赋值运算符一起使用将从显示列表中删除元素elem1,但保留它作为参考以供以后使用。

我不仅需要获取已删除节点的引用,还需要将已删除的节点插入回删除它的同一位置。因此,我不得不使用这样的堆栈:

// Note: This is ES6; for ES5 see https://stackoverflow.com/a/23528539/2065702
const stack = [];
function removeWithStack() {
    const elem = this,
          parent = elem.parentNode;
    
    const action = {
        "index": Array.from(parent.children).indexOf(elem),
        "parent": parent,
        "elem": parent.removeChild(elem)
    }
    
    stack.push(action);
}
function popAddStack() {
    const action = stack.pop();
    action.parent.insertBefore(action.elem, action.parent.children[action.index]);
}

const ps = document.querySelectorAll("p");
// Note: This is ES6; for ES5 see https://stackoverflow.com/a/23528539/2065702
const stack = [];
function removeWithStack() {
    const elem = this,
          parent = elem.parentNode;
    const action = {
        "index": Array.from(parent.children).indexOf(elem),
        "parent": parent,
        "elem": parent.removeChild(elem)
    }
    stack.push(action);
}
function popAddStack() {
    const action = stack.pop();
    action.parent.insertBefore(action.elem, action.parent.children[action.index]);
}
document.querySelector("button").onclick = popAddStack;
ps.forEach(function(p) {
    p.onclick = removeWithStack;
});
button,
p {
    cursor: pointer;
}
<div>
    <p>Test 1</p>
    <p>Test 2</p>
    <p>Test 3</p>
    <p>Test 4</p>
    <p>Test 5</p>
</div>
<button>Undo</button>

最新更新