gpt4 book ai didi

javascript - 计算和限制文本区域中的单词

转载 作者:技术小花猫 更新时间:2023-10-29 12:12:48 24 4
gpt4 key购买 nike

我设法制作了这个小的 jquery 函数来计算在 textarea 字段中输入的单词数。

here is the fiddle

代码如下:

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();
});

这里是html代码

<textarea name="txtScript" id="word_count" cols="1" rows="1"></textarea>
Total word Count : <span id="display_count">0</span> words.

我怎样才能修改它以获得这样的输出

总字数:0 个字。剩余字数:200

当它达到 200 个单词时,它不允许在 textarea 字段中粘贴或键入更多单词,在 jquery 中?即,它应限制用户只能键入不超过 200 个单词。

请帮忙。

非常感谢。

编辑:仅此代码需要修改,因为我非常了解插件,但它们可能会干扰主代码。

最佳答案

使用return false 停止keyup 事件不会阻止事件,因为在这种情况下事件已经触发。 keyup 事件在用户释放键时触发,该键的默认操作已执行后。

您需要以编程方式编辑 textarea 的值作为 #wordcount:

$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = 0;

if ((this.value.match(/\S+/g)) != null) {
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);
}
});
});

http://jsfiddle.net/k8y50bgd/

关于javascript - 计算和限制文本区域中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com