Javascript 计算html工作表上多个文本区域的单词数

Javascript 计算html工作表上多个文本区域的单词数,javascript,jquery,textarea,counter,onkeyup,Javascript,Jquery,Textarea,Counter,Onkeyup,我有一个html表单,其中包含几个文本区域(100),它们都有相同的id“edit” 我的问题是,我想把每个人身上的所有单词都一一数一数 我试过一些在互联网上找到的代码,它们在第一个文本区域工作正常,但在第二个文本区域停止工作 我对javascript完全是个新手,我甚至不知道从哪里开始。非常感谢所有的帮助 谢谢如中所述,ID必须是唯一的。您的JavaScript代码失败,因为它符合这一点。它没有理由在匹配第一个ID后继续检查元素。一旦您对ID进行了排序,这非常重要,请使用下面的小提琴来帮助-

我有一个html表单,其中包含几个文本区域(100),它们都有相同的id“edit”

我的问题是,我想把每个人身上的所有单词都一一数一数

我试过一些在互联网上找到的代码,它们在第一个文本区域工作正常,但在第二个文本区域停止工作

我对javascript完全是个新手,我甚至不知道从哪里开始。非常感谢所有的帮助


谢谢

如中所述,ID必须是唯一的。您的JavaScript代码失败,因为它符合这一点。它没有理由在匹配第一个ID后继续检查元素。

一旦您对ID进行了排序,这非常重要,请使用下面的小提琴来帮助-


在这个提琴中,它只是在每个
textarea
中迭代,并在列表中设置一个值。

当您按ID查找元素时,它将只返回一个,因此您的方法不适用于多个元素。您可以做的是迭代id。例如,元素1的id=“edit1”、元素2=“edit2”、元素100=“edit100”等等。通过这种方式,您可以通过一个简单的for循环轻松访问它们:

var rootID = "edit";
var totalWordCount = 0;
for (var i=0; i<100; i++) {
  var textElement = document.getElementById(rootID + i);
  var textBoxContents = textElement.value;

  // Count the words in one textbox.
  var textBoxWordCount = 0;
  // These are optional, they are there to account for new lines or double spaces
  // and will help make your word count more accurate.
  textBoxContents = textBoxContents.replace(/(^\s*)|(\s*$)/gi,"");
  textBoxContents = textBoxContents.replace(/[ ]{2,}/gi," ");
  textBoxContents = textBoxContents.replace(/\n /,"\n");
  // This splits up words and counts them based on whether there is a space 
  // between them or not. 
  textBoxWordCount = textBoxContents.split(' ').length;

  // Add this number of words to the total.
  totalWordCount += textBoxWordCount;
}

// totalWordCount now holds the total number of words in all your boxes!
var rootID=“编辑”;
var totalWordCount=0;

对于(var i=0;i您可以尝试以下方法:

// tas is all your textareas
var tas= document.getElementsByName("textareas"), 
  // or document.getElementsByTagName("textarea")
i,arr=[];
for(i=0;i<tas.length;i++){
  arr.push({
    textareaName:tas[i].name,
    //rough word count
    wordCount:tas[i].value.split(/\b[^\d\w\-]+\b/ig).length
  }];
}
console.log(arr);
//tas是您所有的文本区域
var tas=document.getElementsByName(“textareas”),
//或document.getElementsByTagName(“textarea”)
i、 arr=[];

对于(i=0;i在为所有文本区域设置类而不是ID后,您可以尝试以下操作:

 function countAllWords(){
   var result = 0;
   $(".edit").each(function(){
     var wordcount;
     wordcount = $(this).yourCountingFunction();
     result = result + wordcount;
   });
   return result;
 }

如果它们都有相同的id,那么您就错了。@Jay Blanchard.IDs的唯一性是什么,将一个类用于多个元素如何做到这一点?->//计算单词数,将单词添加到totalWordCount或其他任何您想使用它们的操作。我在回答中添加了更多的实现信息,希望这会有所帮助!