我为wordcount验证编写了以下代码,用于将文本/按键粘贴到textarea中:
$('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);
}
答案 0 :(得分:1)
您正在调用该函数并将结果传递给setTimeout。你需要传递一个函数。
$('textarea[maxlength]').keyup(function(eventObject) {
window.setTimeout(function(){validateLength(eventObject.target)}, 1);
return true;
}