工做中遇到這樣的需求:要求input輸入的最大字符是8個,輸入英文時能夠最多輸入8個英文字符,可是輸入中文時,會出如今輸入了四個漢字以後,就不能在輸入了,緣由在於一個漢字佔了兩個字節。javascript
如何解決這個問題,即英文和漢字都最多輸入8個,而不是按位來計算?html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta charset="utf-8"> 6 </head> 7 <body> 8 <input type="text" name="input1" id="str" value="" placeholder="請輸入字符串"> 9 <input type="text" name="length" value="" id="leng"> 10 <button onclick="GetLength()">測試</button> 11 <script type="text/javascript"> 12 var GetLength = function() { 13 var str = document.getElementById("str"); 14 var str1 = str.value; 15 ///<summary>得到字符串實際長度,中文2,英文1</summary> 16 ///<param name="str">要得到長度的字符串</param> 17 var realLength = 0, len = str1.length, charCode = -1; 18 for (var i = 0; i < len; i++) { 19 charCode = str1.charCodeAt(i); 20 if (charCode >= 0 && charCode <= 128){realLength += 1; 21 }else{ 22 realLength += 2;} 23 } 24 var objLength = document.getElementById("leng"); 25 objLength.value = realLength; 26 27 }; 28 29 // 執行代碼: 30 //alert(jmz.GetLength($('#userid').val())); 31 32 33 </script> 34 </body> 35 </html>