CKEditor 實例運行在 <textarea> 之上,編輯器內容變更不會自動同步回原生 textarea.value。表單原生提交時,後端收到的仍是初始值。解決方案極簡:提交前調用 updateElement()。
// 方式 1:表單 onsubmit 事件
document.getElementById('myForm').addEventListener('submit', function() {
for (const instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
});
// 方式 2:jQuery 提交前
$('#myForm').on('submit', function() {
for (const instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
});
// 方式 3:AJAX 序列化前(如 $.ajax / axios)
function serializeFormWithCKE(form) {
for (const instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
return $(form).serialize(); // 或 new FormData(form)
}
CKEDITOR.instances.updateElement() 靜態方法// 一行搞定所有實例
CKEDITOR.instances.updateElement();
// 或針對特定實例
CKEDITOR.instances['editor1'].updateElement();
<textarea> 替換為 <iframe> (經典模式) 或 <div contenteditable> (內聯模式)textareaupdateElement() 將編輯器最新 HTML 同步回 textarea.valueFormData / $.serialize() 讀取的都是 textarea.valueCKEDITOR.replace('editor1', {
// 每次輸入同步,會觸發大量 textarea 更新
on: {
instanceReady: function() {
this.on('change', function() { this.updateElement(); });
}
}
});
textarea,直接操作模型數據editor.getData() 返回 HTML 字符串input 或直接發送 JSONupdateElement() → 後端收到舊數據CKEDITOR.replace() 之前調用 → 實例不存在報錯CKEDITOR.instances$(form).serialize() 但未先同步 → 同理表單提交前(原生/AJAX 統一),執行 CKEDITOR.instances.updateElement()。這是 CKEditor 4 官方文檔明確要求的「必要步驟」。封裝為通用工具函數或框架組件生命周期鉤子,一次配置,永久免維護。