kindeditor添加字节计算方法,解决中文字节数问题

北战南征 提交于 2019-12-04 05:43:19

前情提要:项目中使用kindeditor做富文本编辑器,但是中文在数据库中占用3个字节,英文是1个字节,而p标签换行标签也各自占用对应的代码长度字节.

kindeditor版本 @version 4.1.2 (2012-07-21)

页面使用以下代码计数

js:

afterChange : function() {K('.word_count').html(this.count());}

 html:

<p>您当前输入了 <span class="word_count">0</span> 个文字。</p>

问题:由于kindeditor自带的计数器是按照字符来计算的,所以呢,如果按照它提供的字符数提交到数据库

所以Google之后.找到一个过滤字符Unicode来计数的方式,略加修改,添加到kindeditor.js的count(位于5111行)方法后面,取名countCode.  

countCode : function() {
	var self = this,
	total = 0,
        i,
        str = _removeBookmarkTag(_removeTempTag(self.html())),
        len;
	for(i = 0, len = str.length; i < len; i++){
            charCode = str.charCodeAt(i);
            if(charCode <= 0x007f) {
                total += 1;
            }else if(charCode <= 0x07ff){
                total += 2;
            }else if(charCode <= 0xffff){
                total += 3;
            }else{
                total += 4;
            }
        }
	return total;
	},

相应的页面要调用的js也要修改.

afterChange : function() {K('.word_count').html(this.countCode());}

 事后添加:

修改kindeditor-min.js

搜索"count:"在其后添加

countCode:function(){var a=0,i,b=V(ab(this.html())),c;for(i=0,c=b.length;i<c;i++){d=b.charCodeAt(i);if(d<=0x007f){a+=1;}else if(d<=0x07ff){a+=2;}else if(d<=0xffff){a+=3;}else{a+=4;}}return a;},

这样你就可以再页面使用kindeditor-min.js啦.

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!