gpt4 book ai didi

计算输入框输入字数的JavaScript代码

转载 作者:行者123 更新时间:2023-11-30 00:12:00 24 4
gpt4 key购买 nike

我应该写一个函数来计算文本区域中的单词,但我的代码只计算第一个单词,你可以在这里看到代码:

link to my code

var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor){
var myTextareaElement =document.getElementById("myWordsToCount").value;
var haveByNow = 0;
for (var i = 0; i < wordcount.length; i++)
if (wor[i] === " ") {
haveByNow = +1;
}
haveByNow += 1;
document.getElementById("wordcount").innerHTML = haveByNow;
}

最佳答案

为什么不拆分文本区域值的空字符并获取数组长度:
检查下面的片段

var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor) {

var myText = this.value.trim();
var wordsArray = myText.split(/\s+/g);
var words = wordsArray.length;


document.getElementById("wordcount").innerHTML = words;
};
<textarea id="myWordsToCount"></textarea>

<span id="wordcount"></span>

关于计算输入框输入字数的JavaScript代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36093291/

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