这是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 以内。
当我们在文本区域中输入时,它工作正常,并且它会计数,当它达到 200 时,它不允许写入更多内容,但是当我复制粘贴代码时,它一直保持在 200 以上,我该如何纠正这个问题?
这是 fiddle
提前致谢
最佳答案
首先,您的代码更正正在更新
here
和 here 是复制粘贴字数限制的演示,您可以将其集成到代码中。
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
最后调用 am_cal() 函数。
关于javascript - 粘贴文本时基于字数限制文本输入的 jQuery 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18693525/