JQuery - 恢复被替换的元素

JQuery - Restore Element That was Replaced

本文关键字:元素 替换 恢复 JQuery      更新时间:2023-09-26

我有按钮编辑按钮保存。当我单击编辑按钮时,它会用textboxtextarea替换我的元素。如果我单击按钮保存,它使用另一个功能,如何将元素恢复到replaceWith()之前的状态?

<div class="will-be-turned-into-texbox"></div>
function edit(){
    // Replace above div with texbox
}
function save_edit(){
    // Change back texbox to the original div
}

replaceWith文档中,有一个提示:

说明:将匹配元素集中的每个元素替换为提供的新内容,并返回已删除的元素集

(我的强调)

所以。。。存储返回值,当您想将其放回时,请使用append或(实际上)再次replaceWith将其放回。

无端的例子:

var replaced;
$(document).on("click", "#replace", function() {
  // Save what's being replaced
  replaced = $(this).replaceWith('<button id="restore">Restore</button>');
});
$(document).on("click", "#restore", function() {
  // Restore it
  $(this).replaceWith(replaced);
});
<button id="replace">Replace</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

请注意使用委托的事件处理程序,以避免重新连接事物。