我正在尝试计算在textarea字段中输入的单词数。如果字数少于500个字,我想显示“您的文字少于500个字”,如果字数超过500个字,它应该显示“很好!您的文字超过500个字”。我该如何实现?
$(document).ready(function()
{
var wordCounts = {};
$("#my_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_word_count').html(finalCount);
am_cal(finalCount);
}).keyup();
});
<textarea name="txtScript" id="my_word_count" cols="100" rows="10"></textarea>
<br>Total word Count : <span id="display_word_count">0</span> words.
答案 0 :(得分:0)
我不建议计算单词边界,而是建议计算实际单词。
shutterHasBeenPressed = False
$(document).ready(function() {
var $wordCountDisplay = $('#display_word_count');
var $wordCountDisplayMessage = $('#display_word_count_message');
var desiredMinimumWordCount = 10;
$('#my_word_count').on('input', function (e) {
var wordCount = ( e.target.value.match(/\w+/g) || [] ).length;
$wordCountDisplay.text(wordCount);
if (wordCount < desiredMinimumWordCount) {
$wordCountDisplayMessage.text('Your text is below '+ desiredMinimumWordCount +' words please write some more');
$wordCountDisplayMessage.removeClass('greatJob');
} else {
$wordCountDisplayMessage.text('Great job! Your text is over '+ desiredMinimumWordCount +' words');
$wordCountDisplayMessage.addClass('greatJob');
}
}).trigger('input');
});
.greatJob { color: blue; }