gpt4 book ai didi

用于文本输入的 Javascript 字符限制计数器函数

转载 作者:行者123 更新时间:2023-11-30 13:24:34 25 4
gpt4 key购买 nike

我用 javascript 制作了一个计数器,向用户显示某些文本输入或文本区域的字符剩余情况(从设定的限制)。这是代码:

<script type="text/javascript">
function CountRemaining()
{
var limit = 1000;
var count = document.getElementById('press-form-body').value.length;
document.getElementById('counter').innerHTML = ((limit-count) + " characters left");
var timer = setTimeout("CountRemaining()",50);
}
</script>

我上面的令人厌恶的工作正常,但我的问题是我需要多次使用它,并且每次我需要时都创建一个单独的函数,至少可以说这是不切实际的。

我试过了,没用:

<script type="text/javascript">
function CountRemaining(string, targetcounter, limit)
{
var count = document.getElementById(string).value.length;
document.getElementById(targetcounter).innerHTML = ((limit-count) + " characters left");
var timer = setTimeout("CountRemaining()",50);
}

然后我想我为计时器输入了错误的语句,所以我将其更改为这个但仍然没有用:

var timer = setTimeout("CountRemaining(string, targetcounter, limit)",50);

我迷路了。任何帮助将不胜感激。谢谢!

最佳答案

我认为更好的办法是对这些类型的元素使用“onchange”事件。

基本上一旦文本区域/文本输入失去焦点并发生变化,您就可以绑定(bind)一个函数来计算剩余的字符数。

document.getElementById('press-form-body').onchange = function() {
// your stuff (double check this to make sure the "this" value is right
// use this as an example
document.getElementById(targetcounter).innerHTML = this.value.length - 1000
}

另一种解决方案是使用“键”事件来监听输入中的任何按键。

 document.getElementById('press-form-body').onkeypress = function() {
// your stuff (double check this to make sure the "this" value is right
// use this as an example
document.getElementById(targetcounter).innerHTML = this.value.length - 1000
}

关于用于文本输入的 Javascript 字符限制计数器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967449/

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