前情提要:项目中使用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啦.
来源:oschina
链接:https://my.oschina.net/u/94460/blog/82017