+ -
当前位置:首页 → 问答吧 → 帮忙看看这段控制textarea字符长度的代码哪有问题?

帮忙看看这段控制textarea字符长度的代码哪有问题?

时间:2010-04-15

来源:互联网

复制代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>无标题文档</title>
  6. <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"/>
  7. <script type="text/javascript">
  8. function checkLength(){
  9.     var curLength = $("#test").value.length;
  10.     //alert("已经输入的字数:" + curLength );
  11.     if (curLength>150){
  12.         alert("超过字数限制,多出的字将被截断!" );
  13.         $("#test").value = $("#test").value.substr(0,150);
  14.         curLength = 150;
  15.     }
  16.     $("#textCount").innerHTML = 150-$("#test").value.length;
  17. }
  18. $(function(){
  19.     if(/msie/i.test(navigator.userAgent)){
  20.         $("#test").onpropertychange = checkLength;
  21.     } else {
  22.         $("#test").addEventListener("input",checkLength,false);
  23.     }
  24. });
  25. </script>
  26. </head>
  27. <body>
  28. <label>
  29. 剩下<span id="textCount">150</span><br />
  30. <textarea id="#test" cols="45" rows="5"></textarea>
  31. </label>
  32. </body>
  33. </html>


>,< 要兼容firefox跟ie

作者: Ben   发布时间: 2010-04-15