百度UEditor编译器中获取HTML和添加HTML问题

来源:互联网 发布:文章网站数据库设计 编辑:程序博客网 时间:2024/05/17 22:51

今天项目中需要获取百度UEditor编译器中的内容存入数据库,然后又需要将数据库中查询出来的html添加到编译器中,在网上找了到了些方法,但是不是很理想,最后自己查官网API才解决;


1、先说获取百度UEditor编译器中的HTML内容:

之前看帖子有人说用

editor.getPlainTxt();
方法,发现取到的内容,前后的<p></p>标签都没有了,属于单纯的文本文件,后来看了官网说明,才发现这是取文本文件的方法,要想获取直接可以用的html,只有另外两种:

 //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p> var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
 //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p> var content = editor.getAllHtml(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
这两种只是前一种会剔除前后空格,包括</br>这种,推荐用第一种,减少数据库的存储空间。

官网链接:http://ueditor.baidu.com/doc/#UE.Editor:getContent()

2、再说下添加HTML内容百度UEditor编译器中:

先找了个方法:

http://blog.csdn.net/askycat/article/details/61206818

首先非常尊重作者的提点,查阅了百度UEditor的API,execCommand方法确实很强大,

execCommand方法的官网链接:

http://ueditor.baidu.com/doc/#UE.Editor:execCommand(String)

作者的这句话:

UE.getEditor('editor').execCommand('insertHtml', '${queryArtid.aContent }');
其中“insertHtml”参数是添加 hmtl 的命令,后面的时添加内容;

具体命令API官网上也有说明:

http://ueditor.baidu.com/doc/#COMMAND.LIST

接下来说下个人发现的问题:

我按照作者的思路,在jsp中添加了<code>标签

<script id="editor" type="text/plain" style="width: 100%; height: 50%;"></script><code id="content" style="display:none;">        ${content}    </code>
然后js中这样写:

var editor = new UE.ui.Editor();editor.render('editor');var content_old = $('#content').html();editor.execCommand('insertHtml', content_old);
就遇到了像作者一样的延迟赋值问题,主要原因就是因为UEditor没有加载完成,execCommand方法没有执行。

作者采用的办法是添加1秒后的延时操作,但这种方案个人尝试后发现页面会出现闪屏,效果不好。

查阅官网API,发现了ready事件,专门可以针对UEditor加载完成后的处理;

http://ueditor.baidu.com/doc/#UE.Editor:ready

官网上有两种ready的事件的处理方法:

第一种是ready监听:

editor.addListener( 'ready', function( editor ) {     editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点 } );
第二种类似于jquery的$(document).ready{}一样,也是初始完成之后执行:
 editor.ready( function( editor ) {     editor.setContent('初始化完毕'); } );

这两种的效果是一样的。

最后我的js代码改成:

//百度UEditorvar editor = new UE.ui.Editor();editor.render('editor');editor.addListener( 'ready', function(edt) {var content_old = $('#content').html();if(content_old!=''){editor.execCommand('insertHtml', content_old);} });
注意:上述两种方法,官网上的demo有个错误,就是function(editor)中的editor不是Editor()对象而下方

editor.execCommand('insertHtml', content_old);

editor应该是Editor()对象,否则会报“无效属性execCommand”的错误!

所以,我这里把function(editor)改为了function(edt),这样就不会出现变量名冲突;

进过实践,完美解决问题大笑

原创粉丝点击