0

我有一个包含几个文本区域(100)的 html 表,它们都有相同的 id“编辑”。

我的问题是我想单独计算每个人的所有单词......

我尝试了一些我在互联网上找到的代码,它们在第一个 textarea 上运行良好,但在第二个 textarea 上停止运行......

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

谢谢

4

5 回答 5

1

当您通过 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!
于 2013-05-16T15:22:34.533 回答
0

在为所有文本区域设置一个类而不是一个 ID 后,您可以尝试以下操作:

 function countAllWords(){
   var result = 0;
   $(".edit").each(function(){
     var wordcount;
     wordcount = $(this).yourCountingFunction();
     result = result + wordcount;
   });
   return result;
 }
于 2013-05-16T15:27:24.877 回答
0

一旦你对你的 ID 进行了排序,这非常重要,请使用以下小提琴来帮助 - http://jsfiddle.net/dXcLH/1

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

于 2013-05-16T15:22:28.367 回答
0

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

于 2013-05-16T15:13:36.643 回答
0

你可以尝试这样的事情:

// 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);

在 Chrome 中检查此代码,按 F12 并在控制台中查看 arr 变量,您可以单击它来检查它的值。

于 2013-05-16T15:26:00.697 回答