文章目錄
limit.js代碼
//txt:文字框jquery對象//limit:限制的字數//isbyte:true:視limit為位元組數;false:視limit為字元數//cb:回呼函數,參數為可輸入的字數 function InitLimit(txt,limit,isbyte,cb){txt.keyup(function(){var str=txt.val();var charLen;var byteLen=0;if(isbyte){//原文部落格:blog.csdn.net/bluceyoungfor(var i=0;i<str.length;i++){if(str.charCodeAt(i)>255){byteLen+=2;}else{byteLen++;}}charLen = Math.floor((limit-byteLen)/2);}else{byteLen=str.length;charLen=limit-byteLen;}cb(charLen);});}頁面代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"> </script> <script type="text/javascript" src="limit.js"></script><script type="text/javascript"> $(document).ready(function(){ InitLimit($("#txt"),10,true,function(c){ if(c>=0){ $("#show").val("還能輸入"+c+"個字"); }else{ $("#show").val("已經超過"+(-c)+"個字"); } }); InitLimit($("#txt1"),10,true,function(c){ if(c>=0){ $("#show1").val("還能輸入"+c+"個字"); }else{ $("#show1").val("已經超過"+(-c)+"個字"); } }); }); </script> </head> <body> <input type="text" id="txt"/><input id="show" type="text"/><br/><input type="text" id="txt1"/><input id="show1" type="text"/></body> </html>
: