我在keyup上有以下绑定,如果它们超过150个字符就会发出警告,但你可以按下okay并继续键入然后继续按下就可以了.
我想以150个单词(不是字符)裁剪它们,如果它们键入它,则删除附加内容.但我似乎无法弄明白该怎么做,我可以搞清楚角色.但不是言语.
jQuery('textarea').keyup(function() {
var $this,wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > 150) {
jQuery(".word_count span").text("150");
return alert("You've reached the maximum allowed words.");
} else {
return jQuery(".word_count span").text(wordcount);
}
});
解决方法
如果您想阻止输入本身(当计数> 150时),您可以执行以下操作:
>使用按键而不是键盘
>而不是返回alert()首先执行alert()然后返回false;
您可能还想添加更改(或模糊)事件处理程序来处理文本粘贴.
var maxWords = 150;
jQuery('textarea').keypress(function() {
var $this,wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
jQuery(".word_count span").text("" + maxWords);
alert("You've reached the maximum allowed words.");
return false;
} else {
return jQuery(".word_count span").text(wordcount);
}
});
jQuery('textarea').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {
words.splice(maxWords);
$(this).val(words.join(""));
alert("You've reached the maximum allowed words. Extra words removed.");
}
});
Fiddle here