jQuery函数,用于在粘贴文本时限制基于单词计数的文本输入
这是jquery代码
var max_count = 200;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function (k, v) {
finalCount += v;
});
var vl = this.value;
if (finalCount > max_count) {
vl = vl.substring(0, vl.length - 1);
this.value = vl;
}
var countleft = parseInt(max_count - finalCount);
$('#display_count').html(finalCount);
$('#count_left').html(countleft);
am_cal(finalCount);
}).keyup();
});
此代码的工作是计算单词数量并限制它们上升200.
The work of this code is to count the number of words and limit them going up 200.
当我们输入textarea它工作正常,它很重要,当它达到200时它不允许写更多,但当我复制粘贴代码时,它继续200以上,我怎么能纠正这个?
When we type in the textarea it works fine, and it counts and when it reaches 200 it does not allow to write more, but when i copy paste the code, it keeps going above 200, how can i correct this?
这里是小提琴
提前致谢
首先,您的代码更正已更新
这里
First of all, your code correction is being updated
here
和 这里 是一个关于复制粘贴的字数限制的演示,您可以将其集成到您的代码中。
and here is a demo for word limit on copy paste you can integrate it in your code.
jQuery(document).ready(function($) {
function limits(obj, limit){
var text = $(obj).val();
var length = text.length;
if(length > limit){
$(obj).val(text.substr(0,limit));
} else {
/**
* Alerts the user of the remaining characters.
* I do alert here, but you can do any other thing you like.
*/
alert(limit - length + " characters remaining!");
}
}
$('textarea').keyup(function() {
limits($(this), 20);
});
});
您的完整代码根据您的要求 HERE
your complete code according to your requirement HERE
最后调用你的am_cal()函数。
call your am_cal() function at the end.