<!doctype html> <html> <head> <meta charset="utf-8"> <title>jQuery实现限制input框 textarea文本框输入字符数量的方法</title> </head> <script src="http://j2.58cdn.com.cn/js/jquery-1.8.3.js"></script><!--依赖jquery--> <body> 用户名:<input type="text" name="username" id="username" > <span style="display:none;border:0;float:right;margin-right:50px" id="t2" >用户名长度为3-6位</span> <!--我微信号 (WX-APP-PC) --> <script> (function($) { $.fn.extend( { limiter: function(limit, elem) { $(this).on("keyup focus", function() { setCount(this, elem); }); function setCount(src, elem) { var chars = src.value.length; if (chars > limit) { src.value = src.value.substr(0, limit); chars = limit; $(‘#t2‘).show(); }else{ $(‘#t2‘).hide(); } elem.html( limit - chars ); } setCount($(this)[0], elem); } }); })(jQuery); //To setup the limiter, simply include a call similar to the one below: var elem = $("#username"); $("#username").limiter(6, elem); </script> </body> </html>