xheditor插件无限递归错误解决方法
$.fn.oldVal = $.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(_this[0]&&(editor=_this[0].xheditor))return editor.getSource();else return _this.oldVal();//读
return _this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
问题分析:
-
代码将
$.fn.oldVal = $.fn.val保存原val()方法 -
然后在新的
val()方法中又调用了_this.oldVal() -
由于
oldVal实际上就是原val()方法,但在某些情况下可能又调用了新的val(),导致无限递归
解决方案:
方案1:修复 xheditor 的 val 方法(推荐)
修改 $.fn.val 的实现,避免无限递归:
// 修改前的问题代码
$.fn.oldVal = $.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(_this[0]&&(editor=_this[0].xheditor))return editor.getSource();else return _this.oldVal();//读
return _this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
// 修改后的代码
$.fn.oldVal = $.fn.val;
$.fn.val = function(value) {
if (value === undefined) {
// 读取值
if (this[0] && this[0].xheditor) {
return this[0].xheditor.getSource();
}
// 直接调用 jQuery 原生的 val 方法
return jQuery.fn.val.call(this);
}
// 设置值
return this.each(function() {
if (this.xheditor) {
this.xheditor.setSource(value);
} else {
// 直接调用 jQuery 原生的 val 方法
jQuery.fn.val.call($(this), value);
}
});
}
方案2:使用兼容性更好的方式
或者使用更安全的方式,直接调用原始的 jQuery 方法:
// 保存原始方法
var originalVal = $.fn.val;
$.fn.val = function(value) {
var _this = this;
// 读取操作
if (value === undefined) {
if (_this[0] && _this[0].xheditor) {
return _this[0].xheditor.getSource();
}
// 调用原始 val 方法
return originalVal.call(_this);
}
// 写入操作
return _this.each(function() {
if (this.xheditor) {
this.xheditor.setSource(value);
} else {
// 调用原始 val 方法
originalVal.call($(this), value);
}
});
};
方案3:临时解决方法
如果你需要快速解决问题,可以在加载 xheditor 后添加以下代码:
// 在 xheditor 加载后执行
$(function() {
// 修复无限递归问题
var originalVal = $.fn.val;
$.fn.val = function(value) {
var _this = this;
if (value === undefined) {
if (_this[0] && _this[0].xheditor) {
return _this[0].xheditor.getSource();
}
return originalVal.call(_this);
}
return _this.each(function() {
if (this.xheditor) {
this.xheditor.setSource(value);
} else {
originalVal.call($(this), value);
}
});
};
});
根本原因:
这个问题通常发生在:
-
jQuery 版本升级(特别是从旧版本升级到 3.x)
-
多次加载 xheditor 插件
-
与其他插件冲突
建议使用方案1或方案2直接修改 xheditor 源码,这样可以一劳永逸地解决问题。
浙公网安备 33010602011771号