ash*_*his 16 html javascript jquery
我设法使这个小jquery函数计算在textarea字段中输入的单词数.
这是代码:
JQUERY:
$(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;
});
$('#display_count').html(finalCount);
am_cal(finalCount);
}).keyup();
});
Run Code Online (Sandbox Code Playgroud)
这是html代码
<textarea name="txtScript" id="word_count" cols="1" rows="1"></textarea>
Total word Count : <span id="display_count">0</span> words.
Run Code Online (Sandbox Code Playgroud)
如何在其中进行修改以获得这样的输出
总字数:0字.剩下的话:200
当它达到200个单词时,它不允许在jquery中粘贴或在textarea字段中输入更多单词?即它应限制用户输入不超过200字的字.
请帮忙.
非常感谢提前.
编辑:此代码只需要修改,因为我非常了解插件,但它们可能会干扰主代码.
Mic*_*hal 41
用return false停止keyup事件不会阻止的情况下,因为在这种情况下,该事件已经被解雇.在执行该键的默认操作后keyup,用户释放密钥时将触发该事件.
您需要以编程方式编辑textarea您拥有的值#wordcount:
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = this.value.match(/\S+/g).length;
if (words > 200) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).val().split(/\s+/, 200).join(" ");
// Add a space at the end to make sure more typing creates new words
$(this).val(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(200-words);
}
});
});
Run Code Online (Sandbox Code Playgroud)