0

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

elem1.parentNode.removeChild(elem1);
4

3 回答 3

3

正如MDN 文档 removeChild中所写,将返回对已删除子节点的引用。像这样的用法:

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

更远:

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

于 2012-10-02T08:28:54.457 回答
2

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

您可以通过执行以下操作强制 JavaScript 将其存储在内存中以供以后使用/恢复:

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

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

于 2012-10-02T08:29:24.077 回答
1

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

// 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>

于 2018-07-10T17:33:44.437 回答