问题描述
使用 jquery 的 load 方法加载页面时,被加载页面的Kindeditor 控件显示失败。
原因
Kindeditor 代码片段
- function _ready(fn) {
- if (_readyFinished) {
- fn(KindEditor);
- return;
- }
- var loaded = false;
- function readyFunc() { //初始化方法
- if (!loaded) {
- loaded = true;
- fn(KindEditor);
- _readyFinished = true;
- }
- }
- function ieReadyFunc() {
- if (!loaded) {
- try {
- document.documentElement.doScroll('left');
- } catch(e) {
- setTimeout(ieReadyFunc,100);
- return;
- }
- readyFunc();
- }
- }
- function ieReadyStateFunc() {
- if (document.readyState === 'complete') {
- readyFunc();
- }
- }
- if (document.addEventListener) {
- _bind(document,'DOMContentLoaded',readyFunc); //将初始化方法 bind 在 documet 对象上
- } else if (document.attachEvent) {
- _bind(document,'readystatechange',ieReadyStateFunc); <span style="font-family: Arial,Helvetica,sans-serif;">//将初始化方法 bind 在 window 对象上</span>
- var toplevel = false;
- try {
- toplevel = window.frameElement == null;
- } catch(e) {}
- if (document.documentElement.doScroll && toplevel) {
- ieReadyFunc();
- }
- }
- _bind(window,'load',readyFunc);
- }
查看上面代码发现 Kindeditor 控件的初始化方法是 bind 在页面中的 window 和 document 对象的 onload 事件上。
而使用 ajax 方式加载含有Kindeditor 控件的页面,是不会触发onload 事件的。
解决方案
经过上面的分析发现Kindeditor 控件这所以不显示是因为没有触发window 和document 的 onload 事件。
所以只要在加载完含有Kindeditor 控件的页面后手动触发一次 onload 事件即可。
- //chorme,firefox
- var event = document.createEvent('HTMLEvents');
- event.initEvent("load",true,true);
- window.dispatchEvent(event);
- //ie
- if(document.createEventObject){
- var event = document.createEventObject();
- window.fireEvent('onload',event);
- }