如何解决如何每秒将字符串值增加 1 JS
我有一个值 var x = "2"
。我怎样才能每秒增加 x 以便从我定义 x 开始的一秒,x 等于 3?
我的代码如下所示:
<img src="cookie.jpg" style="text-align:center; width:250px;" id="cookie" onclick="Click()">
<h1 id="score">0</h1>
<script>
var cookie = document.getElementById("cookie");
function Click() {
var scoreStr = document.getElementById("score");
var score = parseInt(scoreStr.textContent);
score ++;
scoreStr.textContent = score;
}
</script>
解决方法
使用 setInterval 并将其设置为一秒 => 1000
let display = document.getElementById('display')
let x = display.textContent;
// textContent returns a string value
setInterval(()=>{
// lets change the string value into an integer using parseInt()
// parseInt would not be needed if the value of x was `typeof` integer already
display.textContent = parseInt(x++)
},1000)
<div id="display">2</div>
您可以使用javascript setInterval 函数https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
例如:
var x = 0;
setInterval(() => {
x = x + 1;
},1000); //1000ms = 1 second
然后每一秒都会增加“x”变量。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。