我不确定标题是否正确。我似乎无法用语言正确表达这个问题!
我的 HTML 中有以下文本字段,我试图限制可以输入的字符数:
<div class="limited limit-200">
    <div class="label">
        <label for="_je_industries_desc">Industry Description</label>
    </div>
    <div class="input">
        <textarea class="large-text" name="industries_desc" id="industries_desc" cols="60" rows="3"></textarea>
        <p id="industries_desc_description" class="description">Put a short description of this industry.</p>
    </div>
</div>
<div class="limited limit-100">
    <div class="label">
        <label for="_je_seo_description">Meta Description</label>
    </div>
    <div class="input">
        <textarea class="large-text" name="seo_description" id="seo_description" cols="60" rows="3"></textarea>
        <p id="seo_description_description" class="description">Put a short description of the content of this page.</p>
    </div>
</div>
到目前为止,这是我的 jQuery。例如,它从 HTML 中的类名中获取字符限制limit-200。然后计算您键入时剩余的字符数,并在 textarea 下输出剩余的字符。
jQuery(document).ready(function(){
    jQuery('.limited').each(function() {
        // Get the class names of any element that has the class .limited
        var className = jQuery(this).attr('class');
        // Use regex to capture the character limit class (limit-#)
        var limit = className.match(/[?:limit-](\d+)/);
        // Set the limit var to the match from the regex
        var limit = limit[1];
        // Calculate the number of characters that are still available (limit - characters in field)
        var chars_left = limit - jQuery('textarea', this).val().length;
        //alert(chars_left);
        // Attach an event handler to each textarea with the class .limited
        jQuery('textarea', this).on('keyup', function() {
            var maxchar = limit;
            var cnt = jQuery(this).val().length;
            var remainingchar = maxchar - cnt;
            if(remainingchar < 0){
                jQuery('#limit-counter span').html('<strong>0</strong>');
                jQuery(this).val(jQuery(this).val().slice(0, limit));
            } else {
                jQuery('#limit-counter span').html('<strong>' + remainingchar + '</strong>');
            }
        });
        // Display number of characters left
        jQuery('textarea', this).after('<span id="limit-counter">Remaining characters: <span><strong>' + chars_left + '</strong></span></span>');
    });
});
这对于单个 textarea 非常有用,但是如果我有多个文本并输入其中一个 textarea,则另一个 textarea 会使用与我输入的相同的值更新其计数器。
有人可以帮我找出我做错了什么吗?希望我只是在某个地方遗漏了一些简单的东西!
谢谢!