4

我的以下代码运行良好,但问题是超过 500 个字符后,它开始允许用户输入(它接受字符而不是限制它们!)。

我该如何修改它?是否有可能概括此代码,以便它可以处理多个文本区域,例如函数并仅传递参数?

 $('#txtAboutMe').keyup(function () {
           var text = $(this).val();
           var textLength = text.length;`enter code here`
           if (text.length > maxLength) {
               $(this).val(text.substring(0, (maxLength)));
               alert("Sorry, you only " + maxLength + " characters are allowed");
           }
           else {
               //alert("Required Min. 500 characters");
           }
       });"
4

3 回答 3

8

你不应该这样做keyup。试试keypress吧。问题在于keyup字符已被触发并写入 textarea。这是一个很好的教程。注意按键事件。

jQuery(function($) {

  // ignore these keys
  var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];

  // use keypress instead of keydown as that's the only
  // place keystrokes could be canceled in Opera
  var eventName = 'keypress';

  // handle textareas with maxlength attribute
  $('textarea[maxlength]')

    // this is where the magic happens
    .live(eventName, function(event) {
      var self = $(this),
          maxlength = self.attr('maxlength'),
          code = $.data(this, 'keycode');

      // check if maxlength has a value.
      // The value must be greater than 0
      if (maxlength && maxlength > 0) {

        // continue with this keystroke if maxlength
        // not reached or one of the ignored keys were pressed.
        return ( self.val().length < maxlength
                 || $.inArray(code, ignore) !== -1 );

      }
    })

    // store keyCode from keydown event for later use
    .live('keydown', function(event) {
      $.data(this, 'keycode', event.keyCode || event.which);
    });

});
于 2011-07-29T18:41:10.057 回答
6

您可以尝试定义一个用于比较的 maxLength(如果未定义等于未定义并且每个数字都大于未定义:这就是我认为您永远不会收到警报的原因):

$('#txtAboutMe').keyup(function () {
           var maxLength = 500;
           var text = $(this).val();
           var textLength = text.length;
           if (textLength > maxLength) {
               $(this).val(text.substring(0, (maxLength)));
               alert("Sorry, you only " + maxLength + " characters are allowed");
           }
           else {
               //alert("Required Min. 500 characters");
           }
       });"
于 2011-07-29T18:46:02.943 回答
0

解决方案有两个:

  • 在插入字母之前使用 keydown 事件而不是 keyup 来捕获事件
  • 使用 preventDefault 阻止插入字母

    $('#txtAboutMe').keyup(function (e) {//note the added e to pass the event data
       var text = $(this).val();
       var textLength = text.length;`enter code here`
       if (text.length > maxLength) {
           $(this).val(text.substring(0, (maxLength)));
           alert("Sorry, you only " + maxLength + " characters are allowed");
           e.preventDefault();
           return;
       }
       else {
           //alert("Required Min. 500 characters");
       }
    

    });

于 2013-10-25T04:55:10.213 回答