2013-04-02 84 views
1

我寫了下面的代碼單詞計數驗證用於粘貼文本/按鍵變成一個textarea:Jquery setTimeout拋出一個「JScript運行時錯誤:無效的參數。」例外?

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

的validateLength功能(如下圖)得到exceuted,但是當它返回到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); 
    } 

回答

1

您正在調用該函數並將結果傳遞給setTimeout。你需要傳遞一個函數。

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

完美,謝謝!!!!! – Chaka

相關問題