JavaScript 富文本编辑器:清空内容与重置表单

区分清空内容、恢复初始文档与表单重置,避免意外丢失未保存的草稿。
清空与重置是两种操作
清空会把当前文档替换为空值;重置会恢复明确指定的初始文档。这两种操作都不会删除数据库记录或已上传的图片。保留同一个编辑器实例,不要用 innerHTML 替换它的 DOM。
运行完整示例
通过应用提供编辑器资源。示例会在破坏性操作前请求确认,取消后保留编辑内容,并在提交时读取最新 HTML。它不发送网络请求。普通标题字段由原生表单恢复,编辑器内容需要明确恢复。
<link rel="stylesheet" href="/richtexteditor/rte_theme_default.css">
<script src="/richtexteditor/rte.js"></script>
<script src="/richtexteditor/plugins/all_plugins.js"></script>
<style>body{font:16px/1.6 system-ui;max-width:960px;margin:24px auto;padding:0 16px}button,input{min-height:44px;box-sizing:border-box}button{padding:8px 16px} .actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:16px}</style>
<h1>Clear or reset a rich text editor</h1>
<form id="note-form">
<label>Title <input name="title" value="Project notes"></label>
<div style="max-width:100%;overflow-x:auto"><div id="editor"></div></div>
<div class="actions">
<button type="button" id="clear">Clear content</button>
<button type="reset">Restore initial form</button>
<button type="submit">Check HTML</button>
</div>
<p id="status" role="status" aria-live="polite"></p>
</form>
<script>
const initialHTML = "<h2>Project notes</h2><p>Keep <strong>this starting document</strong>.</p>";
const editor = new RichTextEditor("#editor", { toolbar: "full", height: "320px" });
const form = document.getElementById("note-form");
const status = document.getElementById("status");
editor.setHTMLCode(initialHTML);
document.getElementById("clear").addEventListener("click", () => {
if (!window.confirm("Clear the current document? This demo has no saved backup.")) return;
editor.setHTMLCode("");
status.textContent = "Content cleared. Title unchanged. Nothing was saved.";
});
form.addEventListener("reset", event => {
if (!window.confirm("Restore the initial title and document?")) {
event.preventDefault();
return;
}
// Native reset restores ordinary fields; explicitly restore the editor.
editor.setHTMLCode(initialHTML);
status.textContent = "Initial form restored. Nothing was saved.";
});
form.addEventListener("submit", event => {
event.preventDefault();
// Read live editor data, not the original markup or a stale hidden field.
const html = editor.getHTMLCode();
status.textContent = "Current HTML: " + html.length + " UTF-16 units. No request sent.";
});
window.resetDemo = { editor, initialHTML };
</script>
协调重置与自动保存
自动保存逻辑可能把重置当作普通编辑。请明确它应被保存、暂停,还是作为新草稿处理。客户端重置不能取消服务器已经接受的写入。串行保存、检查版本,并等待保存确认后再告知用户服务器内容已删除。本示例不包含自动保存或存储删除。
集成前的测试清单
分别取消两种确认,检查标题和文档都保留。清空时只清空文档。然后修改两个字段,恢复初始表单。测试键盘提交、长标题和 320px 屏幕。不要承诺撤销一定能恢复程序替换的内容;需要恢复功能时单独保留草稿。