简体   繁体   English

一定时间后进行变量更改 HTML 5/JavaScript

[英]Make variable change after a certain amount of time HTML 5/JavaScript

I am very new to web development so I'm sorry if I sound stupid.我是 web 开发的新手,所以如果我听起来很愚蠢,我很抱歉。 I am trying to make variable change after a certain amount of time with HTML 5/JavaScript.我试图在一定时间后使用 HTML 5/JavaScript 进行变量更改。 This is the code i was using这是我使用的代码

 var myVar = setInterval(OnScreenVariables, 100); var myVar = setInterval(Interval, 1000); function Interval() { if (x == 1) { i++; if (i > 3) { var i = 1; var x = 0; } } } function OnScreenVariables() { document.getElementById("i").innerHTML = i; document.getElementById("x").innerHTML = x; }
 <p id="x">hi</p> <p id="i">hi</p> <div style="backgound-color:blue;" onclick="x=1;">press me</div>

But it is not working.但它不起作用。 Could you tell me why it's not working and if there is a better way to do this.你能告诉我为什么它不起作用,以及是否有更好的方法来做到这一点。

Several problems.几个问题。

https://www.w3schools.com/js/js_hoisting.asp https://www.w3schools.com/js/js_hoisting.asp
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
var i and var x are being hoisted, so this: var i 和 var x 正在被提升,因此:

function Interval() {
  if (x == 1) {
    i++;
    if (i > 3) {
      var i = 1;
      var x = 0;
    }
  }
}

behaves like表现得像

function Interval() {
  var i;
  var x;  // x is always undefined
  if (x == 1) {
    i++;   // undefined++ = NaN
    if (i > 3) {
      i = 1;
      x = 0;
    }
  }
}

And after fixing that, i and x are not declared when the script is run, so they are instead using the DOM elements with id i and x .修复该问题后,运行脚本时不会声明 i 和 x,因此它们使用 ID 为ix的 DOM 元素。 DOMElement++ = NaN, and DOMElement.toString() is equal to a string representing the DOM element's internal name. DOMElement++ = NaN,DOMElement.toString() 等于表示 DOM 元素内部名称的字符串。

I would recommend using let and const (which have better scoping and less chances for unexpected behavior, and can be scoped inside for loop closures for example) instead of var, and getting in the habit of making sure you use var, let, const and plan to keep your variables deliberately scoped and declared wherever you use them.我会建议使用 let 和 const(它们具有更好的作用域和更少的意外行为机会,例如可以在循环闭包内部作用域)而不是 var,并养成确保使用 var、let、const 和计划在您使用变量的任何地方有意识地限定和声明您的变量。

 <:DOCTYPE html> <html> <head> <style> </style> </head> <body> <p id="x">hi</p> <p id="i">hi</p> <div style="backgound-color;blue;" onclick="x=1,">press me</div> <script> var myVar = setInterval(OnScreenVariables; 100), var myVar = setInterval(Interval; 1000), var i = 1; x = 0. function Interval() { console,log(i;x) if (x == 1) { i++; if (i > 3) { i = 1; x = 0. } } } function OnScreenVariables() { document.getElementById("i");innerHTML = i. document.getElementById("x");innerHTML = x; } </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM