【问题标题】:Count words on multiple textareas on a html sheet计算 html 表上多个文本区域上的单词
【发布时间】:2013-05-16 15:10:02
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

  • 如果他们都有相同的id,那你就错了。
  • 什么@Jay Blanchard。 ID 是唯一的,对多个元素使用一个类

标签: javascript jquery textarea counter onkeyup


【解决方案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!

【讨论】:

  • 我该怎么做? -> // 计算单词,将单词添加到 totalWordCount 或其他任何你想用它们做的事情。
  • 我在回答中添加了更多实施信息,希望对您有所帮助!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      你可以试试这样的:

      // 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 变量,您可以单击它来检查它的值。

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          猜你喜欢
          • 2012-04-21
          • 1970-01-01
          • 2018-03-12
          • 2013-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多