【问题标题】:How to do a Word Count on Multiple Textareas using jQuery?如何使用 jQuery 对多个文本区域进行字数统计?
【发布时间】:2015-06-06 20:17:04
【问题描述】:

我已经使用以下 JS 成功地对文本区域进行了字数统计:

   jQuery('span.after-amount').append(' - You have <span class="wordcount">0</span> words.'); 

   jQuery('textarea').on('input', function($) {

      var regex = /\s+/gi;
      var count =  jQuery(this).val().trim().replace(regex, ' ').split(" ").length;

      $('.wordcount').html(count);


    });

我的 HTML:

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea>
<span class="after-amount">You have <span class="wordcount">0</span> words.</span>

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea>
<span class="after-amount">You have <span class="wordcount">0</span> words.</span>

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea>
<span class="after-amount">You have <span class="wordcount">0</span> words.</span>

这是Fiddle

我需要获取每个文本区域的字数,有没有一种简单的方法可以在不单独选择每个文本区域的情况下做到这一点?

【问题讨论】:

    标签: javascript jquery html word-count


    【解决方案1】:

    这是我的解决方案,首先我将您的事件处理程序更改为 keyup,然后使用 $(this) 开始计算每个 textarea 值的长度,以便您获得当前的 textarea。

    $(function(){
       $('textarea').on('keyup', function(){
          var wordsLength = $(this).val().length;
          $(this).next().find('.wordcount').html(wordsLength);
       });
    });
    

    检查此updated jsfiddle。希望这会有所帮助

    【讨论】:

    • 非常感谢!效果很好,只需将 $(this).val().length 更改为 $(this).val().trim().split(' ').length 用于单词而不是字符。
    • 哎呀,我忘了添加那个。好的
    【解决方案2】:

    只是找到.wordcount&lt;li&gt;

    jQuery('textarea').on('input', function($) {
            var regex = /\s+/gi;
            var count =  jQuery(this).val().trim().replace(regex, ' ').split(" ").length;
            jQuery(this).parent().find('.wordcount').html(count);
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多