当前位置:首页 > 巧用Javascript代码来限制文本的字节数

巧用Javascript代码来限制文本的字节数

点击次数:1465  更新日期:2011-01-05
\n

关于文本限制字数的问题,在实际开发中经常用到;主要问题出现在对中文的限制,下面代码就解决关于限制字节数的校验问题。


\n

\n

/*
value: 值;
byteLength:数据库字节长度
title:字段中文名称
attribute:属性名称
使用方法说明:


\n

添加 (1) onkeyup=”limitLength(this.value,100,’名称’,\'name’)”
(2) id=”name” 或【struts标签】styleId=”name”
注意:id名称和 attribute属性名称要一样

例子:
<textarea name=”explain” id=”explain” onkeyup=”limitLength(value,5,
‘语义说明’,\'explain’)” >


\n


\n

<input type=”text” name=”explain” id=”explain” onkeyup=”limitLength(value,5,
‘语义说明’,\'explain’)” >


\n

*/


\n

function limitLength(value, byteLength, title, attribute) {
var newvalue = value.replace(/[^\\x00-\\xff]/g, “**”);
var length = newvalue.length;

//当填写的字节数小于设置的字节数
if (length * 1 <=byteLength * 1){
return;
}
var limitDate = newvalue.substr(0, byteLength);
var count = 0;
var limitvalue = “”;
for (var i = 0; i < limitDate.length; i++) {
var flat = limitDate.substr(i, 1);
if (flat == “*”) {
count++;
}
}
var size = 0;
var istar = newvalue.substr(byteLength * 1 – 1, 1);//校验点是否为“×”

//if 基点是×; 判断在基点内有×为偶数还是奇数
if (count % 2 == 0) {
//当为偶数时
size = count / 2 + (byteLength * 1 – count);
limitvalue = value.substr(0, size);
} else {
//当为奇数时
size = (count – 1) / 2 + (byteLength * 1 – count);
limitvalue = value.substr(0, size);
}
alert(title + “最大输入” + byteLength + “个字节(相当于”+byteLength /2+”个汉字)!”);
document.getElementById(attribute).value = limitvalue;
return;
}

\n