javascript文本字段计数器显示加载以及keyup

时间:2015-02-10 01:05:04

标签: javascript jquery

在对我的问题做出非常有效且有帮助的回复之后:javascript text field counter display我没有其他问题。代码(如下所示)效果非常好,但只能在按键后显示。我如何进行调整,使其不仅可以在按键上更新,还可以在页面加载后显示,以便用户在关注字段并键入之前可以看到字符数?通常(但并非总是),在前一个会话中保存的文本字段中已存在文本,因此它们需要从那里获取。

目前正在使用的代码:

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        var diff = (2550 - $(this).val().length);
        if (diff >= 501) {
            $("#count_4_1").html("<span style=\"color: #55a500;\">Characters remaining: " + diff + "</span>");
        } else if ((diff <= 500) && (diff >= 101)) {
            $("#count_4_1").html("<span style=\"color: #ff6600;\">Characters remaining: " + diff + "</span>");
        } else if (diff <= 100) {
            $("#count_4_1").html("<span style=\"color: #ff0000;\">Characters remaining: " + diff + "</span>");
        }
    });
});

谢谢!

1 个答案:

答案 0 :(得分:1)

除了每个按键之外,您只需要打破该功能并将其命名为onLoad。

$(window).load(function() {
    var countChars = function(elm) {
        var diff = (2550 - $(elm).val().length);
        if (diff >= 501) {
            $("#count_4_1").html("<span style=\"color: #55a500;\">Characters remaining: " + diff + "</span>");
        } else if ((diff <= 500) && (diff >= 101)) {
            $("#count_4_1").html("<span style=\"color: #ff6600;\">Characters remaining: " + diff + "</span>");
        } else if (diff <= 100) {
            $("#count_4_1").html("<span style=\"color: #ff0000;\">Characters remaining: " + diff + "</span>");
        }
    };

    countChars("#input_4_1");
    $("#input_4_1").keyup(function() { countChars(this) } );        
});

但我可以建议稍微重构一下代码:

$(window).load(function() {
    var countChars = function(elm, counter) {
        var diff = (2550 - $(elm).val().length), 
            color = 'ff0000';

        if (diff > 500) { 
            color = '55a500';
        } else if (diff > 100) {
            color = 'ff6600';
        }

        $(counter).html('<span style="color: #' + color + ';">Characters remaining: ' + diff + '</span>');
    };

    countChars('#input_4_1','#count_4_1');
    $("#input_4_1").keyup(function() { countChars(this, '#count_4_1') } );
});