1

テキスト/キープレスをテキストエリアに貼り付けるためのワードカウント検証用に、次のコードを作成しました。

  $('textarea[maxlength]').keyup(function(eventObject) {
              window.setTimeout(validateLength(eventObject.target), 1);
              return true;

validateLength 関数 (以下) が実行されますが、settimeout に戻ると例外がスローされます。

 function validateLength(textareaElement) {
           //get the limit from maxlength attribute
                var limit = parseInt($(textareaElement).attr('maxlength'));
                //get the current text inside the textarea
                var text = $(textareaElement).val();
                //count the number of characters in the text
                var chars = text.length;

                //check if there are more characters then allowed
                if(chars > limit){
                    //and if there are use substr to get the text before the limit
                    var new_text = text.substr(0, limit);

                    alert('The character limit is ' + limit + '. Your text has been trimmed to ' + limit + ' characters.');
                    //and change the current text with the new text
                    $(textareaElement).val(new_text);
                }
                alert(chars);
    }
4

1 に答える 1

1

関数を呼び出して、結果を setTimeout に渡しています。関数を渡す必要があります。

$('textarea[maxlength]').keyup(function(eventObject) {
  window.setTimeout(function(){validateLength(eventObject.target)}, 1);
  return true;
}
于 2013-04-02T18:18:55.827 に答える