百度 UE ueditor 实例化 Cannot set property 'innerHTML' of null 解决方案

 

首先

<script>

     var editor=UE.getEditor('')

     var editor1=UE.getEditor('')

</script>

 

然后

editor.ready(function(){//监听编辑器实例化完成的事件

console.log('编辑器1实例化完成')

editor.setContent('嘿嘿')

})

editor.ready(function(){

console.log('编辑器2实例化完成')

editor1.setContent('哈哈')

})

 

但是当我点击浏览器的后退键返回上一个页面(或者是点击页面上自己设置的后退按钮返回上一个页面)后,再一次进入到编辑器页面,同样调用

editor.setContent('嘿嘿')

editor1.setContent('哈哈')

的方法,浏览器控制台就报错了 Cannot set property 'innerHTML' of null .意思就是需要赋值的对象是null(但为什么没有报undefined呢?答案接下来分析)

而且奇葩的是,editor编辑器内容赋值成功,但是editor1赋值失败.

思前想后,还是去看看ueditor的源码吧.

UE.getEditor = function (id, opt) {
var editor = instances[id];
if (!editor) {
editor = instances[id] = new UE.ui.Editor(opt);
editor.render(id);
}
return editor;
};
源码里的instances是一个初始化的空对象

代码的意思就是:先去页面找是否存在已经实例化的编辑器对象,如果没有,就新生成一个编辑器.否则直接将页面上找到的那个编辑器给返回.再联想到刚才的报错Cannot set property 'innerHTML' of null(而不是undefined,而且控制台也没有输出编辑器2实例化完成),那么真相只有一个! 那就是当你在一次来到编辑器页面时,编辑器早已经存在,都已经存在的编辑器,自然不会触发ready事件,所以自然不能触发卸载ready事件里的setContent事件了.

好奇的小伙伴一定会想到,既然编辑器已经存在了,那么我们把setContent函数调到ready事件外,不就行了吗!!!!  然而,并没有任何luan用.....(设置setTimeout也不行)

 

不过我想说的是,我们就来点简单粗暴的方法吧,ok,再回到ueditor源码

UE.getEditor = function (id, opt) {
var editor = instances[id];
if (!editor) {
editor = instances[id] = new UE.ui.Editor(opt);
editor.render(id);
}
return editor;
};

我们可以跳过上面代码的判断,每一次直接根据js传来的id,生成一个全新的ueditor对象.所以上述代码可以改成:

UE.getEditor = function (id, opt) {

UE.delEditor(id);
var editor = new UE.ui.Editor(opt);
editor.render(id);
return editor;
};

最后附上销毁ueditor的一个方法:(UE.delEditor('editor'))

UE.delEditor = function (id) {
var editor;
if (editor = instances[id]) {
editor.key && editor.destroy();
delete instances[id]
}
};

仔细分析一下源码,进行调试就会发现问题,解决bug

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值