Jquery 字符计数器&;限制器-代码清晰度

Jquery 字符计数器&;限制器-代码清晰度,jquery,jquery-plugins,Jquery,Jquery Plugins,我写了小字符计数器和限制器。 您可以在此处进行测试: jQuery代码: $(document).ready(function() { $('.counter').each(function(index) { $('.counter p span').html('0'); // set character length to 0 $('input', this).keyup(function() { var CounterDiv = $(this).pare

我写了小字符计数器和限制器。
您可以在此处进行测试:

jQuery代码:

$(document).ready(function() {

$('.counter').each(function(index) {

    $('.counter p span').html('0'); // set character length to 0
    $('input', this).keyup(function() {

        var CounterDiv = $(this).parent(); //
        var Limit = $('p', CounterDiv).html().split(' / ')[1];
        var CurrentLength = $(this).val().length;

        if (CurrentLength == Limit) {

            $('p span', CounterDiv).html(CurrentLength);
            return false;

        } else if (CurrentLength > Limit) {

            var str = $(this).val();
            $(this).val(str.substring(0, str.length - 1));
            return false;

        } else {

            $('p span', CounterDiv).html(CurrentLength);

        }
    });

});

 });

你有什么建议我如何改进吗?我对语法不是100%确定。

使用本机html
maxlength
属性进行输入

以下是示例:

html

<input name="input1" type="text" maxlength="8" />

你能抽出一分钟解释一下吗<代码>$(this.parent().find('.var count').text($(this.val().length++“/”++$(this.attr('maxlength'))它只是用来表示你的跨度中的符号。。给我一秒钟,我会添加注释在这种情况下,你没有任何逻辑限制文本框中的值。这是由浏览器本身完成的。
$(document).ready(function() {
    $('.counter').each(function(index) {
        $('.counter p span').html('0'); // set character length to 0
        $('input', this).keyup(function() {
            var $countSpan = $(this).parent().find('.var-count'); // find the count span
            var countValue = $(this).val().length + " / "  + $(this).attr('maxlength'); // format value for count span 'current value lenght / maxlength attribute'
            $countSpan.text(countValue); // set formatted value to your column span
        });
    });
});