所以要做的就是 1. 首先区分出来是两个字节的字符还是一个字节的字符; 2. 使用charCodeAt和String.fromCharCode即可进行相互转换。 代码如下: 复制代码 代码如下: function validatePostponeValue(obj, objLength) { var executeResult = false; var value = obj.value; var byteLen=0,len=value.length; var newValue = ""; if(value) { for(var i=0; i<len; i++) { if(value.charCodeAt(i) > 255) { byteLen += 2; if(byteLen <= 18) { //alert(String.fromCharCode(value.charCodeAt(i))); newValue += String.fromCharCode(value.charCodeAt(i)); } } else { byteLen ++; if(byteLen <= 19) { //alert(String.fromCharCode(value.charCodeAt(i))); newValue += String.fromCharCode(value.charCodeAt(i)); } } } } if(byteLen <= 0) { //alert("不能为空!"); obj.focus(); } else if(byteLen > objLength) { alert("最多只能输入十个汉字(20个字符)。"); obj.focus(); obj.value = newValue;//value.substr(0, objLength -1); } else { executeResult = true; } return executeResult; }
推荐阅读
js实现兼容IE6与IE7的DIV高度
复制代码 代码如下:<body onload="setHeight()"> <script type="text/javascript"> function setHeight() { var PageHeight=$("oPage").scrollHeight var MaxHeight=507 if(PageHeight>MaxHeight) { $("oPageMain">>>详细阅读
本文标题:限制文本框输入N个字符的js代码
地址:http://www.17bianji.com/kaifa2/JS/26407.html
1/2 1