JQuery 在相同的多个项目上循环 CSS class

JQuery loop on multiple items of the same CSS class

我有多个相同的字段class。字数显示正确,但当一个字段收到输入时会更改每个字数的值。此外,如果不存在输入,我希望该字段显示 100 个字数,但它显示 0。关于改进以下代码的建议?

jQuery(document).ready(function() {
//Text area 100 word limit
jQuery('.100_wordCount').text("Word Count: 100");
    jQuery(".100_word_limit").on('keyup', function() {
        var words = this.value.match(/\S+/g).length;
        if (words > 100) {
            // Split the string on first 100 words and rejoin on spaces
            var trimmed = jQuery(this).val().split(/\s+/, 100).join(" ");
            // Add a space at the end to keep new typing making new words
            jQuery(this).val(trimmed + " ");
        }else if(words < 0){ 
            jQuery('.100_wordCount').text("Word Count: 100");
        }else{
            var wordsLeft = 100-words;
            jQuery('.100_wordCount').text("Word Count: " + wordsLeft);
        }
    });
});

我会包装每个文本区域 + 字数(例如在 div 中),并在 keyup 事件中根据共享的父元素找到另一个子标签。

此示例仅获取直接父级,但您可以基于共同祖先或其 class 名称来完成。

例如。 http://jsfiddle.net/mzqo2ruk/

Html:

<div>
    <textarea class="100_word_limit"></textarea>
    <p class="100_wordCount"></p>
</div>

Javascript:

jQuery(document).ready(function() {
//Text area 100 word limit
jQuery('.100_wordCount').text("Word Count: 100");
jQuery(".100_word_limit").on('keyup', function() {
        var words = this.value.match(/\S+/g).length;
        if (words > 100) {
            // Split the string on first 100 words and rejoin on spaces
            var trimmed = jQuery(this).val().split(/\s+/, 100).join(" ");
            // Add a space at the end to keep new typing making new words
            jQuery(this).val(trimmed + " ");
        }else if(words < 0){ 
            jQuery(this).parent().find('.100_wordCount').text("Word Count: 100");
        }else{
            var wordsLeft = 100-words;
            jQuery(this).parent().find('.100_wordCount').text("Word Count: " + wordsLeft);
        }
    });
});