使用kindeditor插件报editor is not defined 问题

使用kindeditor插件报editor is not defined 问题

环境

kindeditor-4.1.11-zh-CN

问题描述

相信有很多开发人员需要用到富文本编辑器,而kindeditor就是其中的一种,
在开发过程中不得不需要赋值与获取编辑器的值的操作

ps:以下就是官方给出的代码
// 取得HTML内容
html = editor.html();

// 同步数据后可以直接取得textarea的value
editor.sync();
html = document.getElementById(‘editor_id’).value; // 原生API
html = K(’#editor_id’).val(); // KindEditor Node API
html = $(’#editor_id’).val(); // jQuery

// 设置HTML内容
editor.html(‘HTML内容’);

但是在使用 editor.html(‘HTML内容’); 提示 editor is not defined
条条大路通罗马,这种方法不行,我就换种,无奈尝试了 $(’#editor’).text(‘HTML内容’)、
$(’#editor’).html(‘HTML内容’)、 $(’#editor’).value(‘HTML内容’) 虽然浏览器控制台不报错,
但是内容的值却是一片白板,没有显示。
白板

报错内容、以及代码

图片:
根据官方文档给出的代码
项目运行中报错

解决方案

修改前:

KindEditor.ready(function(K) {
			    var editor = K.create('textarea[name="content1"]', {
				cssPath : '../../kindeditor/js/plugins/code/prettify.css',
				allowFileManager : true,
				afterCreate : function() {
					var self = this;
					K.ctrl(document, 13, function() {
						self.sync();
						document.forms['example'].submit();
					});
					K.ctrl(self.edit.doc, 13, function() {
						self.sync();
						document.forms['example'].submit();
					});
				}
			});
			prettyPrint();
		});

修改后:

KindEditor.ready(function(K) {
			    editor = K.create('textarea[name="content1"]', {
				cssPath : '../../kindeditor/js/plugins/code/prettify.css',
				allowFileManager : true,
				afterCreate : function() {
					var self = this;
					K.ctrl(document, 13, function() {
						self.sync();
						document.forms['example'].submit();
					});
					K.ctrl(self.edit.doc, 13, function() {
						self.sync();
						document.forms['example'].submit();
					});
				}
			});
			prettyPrint();
		});

其实就是把这行的 var 给删除
var editor = K.create(‘textarea[name=“content1”]’, {

解决思路

由于试别的办法不行,无奈还是只能使用官方文档的editor.html(‘HTML内容’)方法,其实这个时候我就大概猜到会不会是因为全局变量的原因?其实很多开发人员都知道,页面开发的时候很多数据都是从后台获取的,这样的话我们的js文件就不仅仅是一个(上传文件可能会单独一个js,获取数据可能会单独一个js等等…),会有多个文件,
那么当定义var editor = K.create(‘textarea[name=“content1”]’, { 这一行的时候由于不是同一个js,那么当我们在赋值的时候使用editor.html(‘HTML内容’)当然会提示 editor is not defined,只要我们设置一下 editor 为全局变量,这样就完美的解决了。

最后

写的不好,有什么错误希望大家指正,共同进步。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值