gpt4 book ai didi

javascript 文本字段计数器显示在加载和按键时显示

转载 作者:行者123 更新时间:2023-12-03 10:50:56 25 4
gpt4 key购买 nike

在对我的问题做出非常有效且有帮助的答复后:javascript text field counter display我没有其他问题了。该代码(如下所示)工作得很好,但它仅在按键后显示。我如何调整它,以便它不仅在按键时更新,而且在页面加载后显示,以便用户在专注于字段和键入之前可以看到字符数?通常(但并非总是),从上一个 session 保存的文本字段中已经有文本,因此它们计数器需要从那里获取。

当前使用的代码:

$(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>");
}
});
});

谢谢!

最佳答案

除了每次按键之外,您只需要分解该函数并调用它 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') } );
});

关于javascript 文本字段计数器显示在加载和按键时显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28422408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com