[英]Update Input field value with javascript
I am trying to build a javascript function that will update an input field every second with a new number. 我正在尝试构建一个javascript函数,该函数将每秒用一个新数字更新输入字段。 This is essentially what I'm hoping my function can do, and hopefully someone can give me a pointer about what I'm doing wrong.
从本质上讲,这就是我希望函数可以完成的工作,希望有人可以给我一些有关我做错了什么的指针。
<script>
var myVar = setInterval(function(){ getNumber() }, 1000);
function getNumber() {
var x = round(microtime(true) * 1000);;
document.getElementById("displaynum").value = x;
</script>
<input type="text" id="displaynum">
Couple of issues you have: 您遇到的几个问题:
Math.round()
and not just round()
Math.round()
,而不仅仅是round()
microtime()
? microtime()
? I have replaced it with Math.random()
to generate a random number. Math.random()
以生成一个随机数。 var myVar = setInterval(function() { getNumber() }, 1000); function getNumber() { var ts = new Date().getTime(); var x = Math.round(ts*Math.random()); document.getElementById("displaynum").value = x; }
<input type="text" id="displaynum">
Update: 更新:
Use new Date().getTime()
to get the current time stamp and couple it with Math.random()
to get a random number with least probability to get repeated. 使用
new Date().getTime()
获取当前时间戳,并将其与Math.random()
耦合以获取随机数,其重复概率最小。
Your approach is correct, but you have some issue with your code such as an undefined function microtime
. 您的方法是正确的,但是您的代码存在一些问题,例如未定义的函数
microtime
。
I've replaced microtime
with a simple counter for the purpose of the example: 就示例而言,我已经用一个简单的计数器代替了
microtime
:
var increment = getNumber(); var input = document.getElementById('displaynum'); var myVar = setInterval(function() { input.value = increment(); }, 1000); function getNumber() { var x = 0; return function() { return x++; } }
<input id="displaynum" type="text" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.