UEDITOR編輯器是百度發(fā)布的一套網(wǎng)站在線編輯器,功能還是比較實(shí)用的,而且兼容性、UI整體都不錯(cuò),很多平臺(tái)都在使用,但是,源代碼模式下編輯完內(nèi)容直接將頁(yè)面表單提交到服務(wù)器,獲取到的表單內(nèi)容不是最新的。
筆者也嘗試過(guò)到到UE的FAQ中找辦法解決,但是,很遺憾沒(méi)有找到任何有價(jià)值的東西,后來(lái)只能到網(wǎng)上尋找解決的辦法,也有網(wǎng)友說(shuō)可能是頁(yè)面中form標(biāo)簽和table標(biāo)簽順序不規(guī)范導(dǎo)致的,經(jīng)過(guò)測(cè)試發(fā)現(xiàn),也不是這個(gè)原因。
沒(méi)辦法,只能去閱讀UE源文件,尋找導(dǎo)致這個(gè)BUG的原因,通過(guò)分析發(fā)現(xiàn),UE編輯器會(huì)監(jiān)聽(tīng)表單事件(有可能是編輯器的blur事件,也可能是表單的submit事件,這個(gè)要具體看config中的參數(shù)設(shè)置),監(jiān)聽(tīng)事件會(huì)根據(jù)編輯器的狀態(tài)變化對(duì)隱藏的textarea表單進(jìn)行內(nèi)容更新,然后,遺憾的是,這個(gè)事件只會(huì)在可視化模式下觸發(fā),而源代碼模式下沒(méi)有這個(gè)事件,從而導(dǎo)致BUG的出現(xiàn)。
好的,找到了BUG的導(dǎo)致原因,那我們就來(lái)想辦法解決,既然源代碼模式下沒(méi)有這個(gè)事件,那我們就加個(gè)事件進(jìn)去,在事件中對(duì)textarea進(jìn)行更新。
實(shí)際上,UE里面的源代碼模式是UE內(nèi)置的一個(gè)plugin,找開(kāi)編輯器主文件,如:ueditor.all.js,找到
// plugins/source.js
/**
* 源碼編輯插件
* @file
* @since 1.2.6.1
*/
(function (){
var sourceEditors = {
textarea: function (editor, holder){
var textarea = holder.ownerDocument.createElement('textarea');
代碼片段,加入一個(gè)函數(shù),以便對(duì)隱藏的表單進(jìn)行更新,修改為以下內(nèi)容
// plugins/source.js
/**
* 源碼編輯插件
* @file
* @since 1.2.6.1
*/
(function (){
var sourceEditors = {
setValue_:function (obj,form,editor){
//為了解決“源代碼模式下直接向服務(wù)端提交表單會(huì)導(dǎo)致服務(wù)端獲取到的表單數(shù)據(jù)不是最新的”的問(wèn)題
var textarea;
if (editor.textarea) {
if (utils.isString(editor.textarea)) {
for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
textarea = ti;
break;
}
}
} else {
textarea = editor.textarea;
}
}
if (!textarea) {
form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
'name': editor.options.textarea,
'id': 'ueditor_textarea_' + editor.options.textarea,
'style': "display:none"
}));
//不要產(chǎn)生多個(gè)textarea
editor.textarea = textarea;
}
!textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea );
textarea.value = obj.value;
},
textarea: function (editor, holder){
var textarea = holder.ownerDocument.createElement('textarea');
其中setValue_就是負(fù)責(zé)更新隱藏表單的JS函數(shù),還是textarea: function (editor, holder)函數(shù),往下看,找到holder.appendChild(textarea);代碼,在它的前面加上
//源代碼模式下直接向服務(wù)端提交表單會(huì)導(dǎo)致服務(wù)端獲取到的表單數(shù)據(jù)不是最新的
if(editor.options.autoSyncData){
domUtils.on(textarea,'blur',function(){
sourceEditors.setValue_(textarea,editor.form,editor);
});
}else{
domUtils.on(editor.form,'submit',function(){
sourceEditors.setValue_(textarea,editor.form,editor);
});
}
代碼,如下圖
好了,保存一下,清空一下網(wǎng)頁(yè)中的緩存,F(xiàn)5刷新一下看看效果!