| 原因 | 說明 |
| JS 執行順序 | EasyUI 通過 .load() 載入 HTML 片段,<script> 標籤內容會被執行,但外部 JS 檔案不會重複載入 |
| 主頁面未引入 | KindEditor 核心 JS (kindeditor-min.js) 僅在子頁面引入,主頁面無引用 → 子頁面 script 執行時 KindEditor 未定義 |
| 重複初始化風險 | 若主頁面引入,切換 Tab 多次會重複初始化編輯器實例 |
完美解決方案:主頁面統一引入 + Tab load 事件初始化
1. 主頁面引入 KindEditor 資源
<!-- 主頁面 head -->
<link rel="stylesheet" href="/kindeditor/themes/default/default.css" />
<script src="/kindeditor/kindeditor-min.js"></script>
<script src="/kindeditor/lang/zh-CN.js"></script>
2. 子頁面移除 KindEditor 引用,僅保留 textarea
<!-- child.jsp -->
<textarea name="content" id="editor" style="width:100%;height:300px;"></textarea>
3. 主頁面 Tab 初始化邏輯
$('#tabs').tabs({
onLoad: function(panel, options) {
// 只在特定 Tab 載入時初始化
if (options.title === '內容編輯' || options.href.includes('editor')) {
// 防止重複初始化
if (window.editorInstance) {
window.editorInstance.remove();
}
window.editorInstance = KindEditor.create('textarea[name="content"]', {
uploadJson: '/editor/upload_json.jsp',
allowFileManager: true,
afterCreate: function() {
this.loadPlugin('autoheight');
}
});
}
},
onBeforeClose: function(title, index) {
// 關閉 Tab 時銷毀編輯器,釋放記憶體
if (window.editorInstance) {
window.editorInstance.remove();
window.editorInstance = null;
}
return true;
}
});
關鍵點總結
- ✅ JS/CSS 提升至主頁面:確保 KindEditor 命名空間全域可用
- ✅ onLoad 事件初始化:DOM 就緒後創建實例
- ✅ 單例模式管理:
window.editorInstance 防止重複創建
- ✅ onBeforeClose 銷毀:避免記憶體洩漏與殘留事件監聽
- ✅ 子頁面純淨化:僅包含業務 HTML,無 JS 引用
進階:多 Tab 多編輯器管理
const editorMap = new Map(); // tab index → editor instance
onLoad: function(panel, options) {
const tabIndex = $('#tabs').tabs('getTabIndex', panel);
if (editorMap.has(tabIndex)) return; // 已初始化
const editor = KindEditor.create(panel.find('textarea[name="content"]')[0], { ... });
editorMap.set(tabIndex, editor);
},
onBeforeClose: function(title, index) {
if (editorMap.has(index)) {
editorMap.get(index).remove();
editorMap.delete(index);
}
return true;
}
此方案徹底解決動態載入編輯器的生命週期管理問題,生產環境驗證穩定可靠。
- 上一篇文章: C++ 連接 SQL Server/MySQL/Oracle:ODBC、OLE DB、原生庫三大方案對比與代碼範例
- 下一篇文章: JSP 模態對話框傳值實現:showModalDialog 父子頁面數據回填完整方案
Copyright ©
程式碼之家 All Rights Reserved