保存当前值并将其与 JavaScript 中变量的新值进行比较

Save the current value and compare it with the new value of a variable in JavaScript

我通过 api 获得了 json 格式的信息,收到了一种货币的价格并使用 JavaScript 将其显示在屏幕上。当然,我将这些放在一个函数中,ajax 每 x 秒更新一次信息。

我需要一个代码,取价格的当前值,收到的价格的下一个值比较这两个,如果新价格高于前一个,例如,背景变绿或给出警报。如果小于前一个,背景会变成红色。

我的代码:

var auto_refresh = setInterval(
  function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("bids1").innerHTML = myObj.BTCUSDT['bids']['0']['0'];
      }
    };
    xmlhttp.open("GET", "all.json", true);
    xmlhttp.send();

  }, 1000);

更正

请参考上面 mplungjan 的回答以获得更正确的方法。虽然按照我指定的方式添加变量是处理此问题的好方法,但您现有的定期检索数据的方法 不是 正确的方法,您应该考虑按照指定的方式更改它来自 mplungjan!

原回答

我通常建议使用全局变量(或至少在您的函数之外)来保持当前价格,并将检索到的值与此进行比较。

// initialize the current price
let currentPrice = 0;

var auto_refresh = setInterval(function () {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            
            let newPrice = myObj.BTCUSDT['bids']['0']['0'];

            if (newPrice > currentPrice) {
                // alert, set some other attribute, etc.

            }

            // update the global variable and the HTML
            currentPrice = newPrice;
            document.getElementById("bids1").innerHTML = currentPrice;
        }
    };
    xmlhttp.open("GET", "all.json", true);
    xmlhttp.send();

}, 1000);

根据您的要求,您当然也可以在您的 http 请求处理程序中进行不同的检查和比较。

不要在 Ajax

上使用间隔
let val = 0;
const bids = document.getElementById("bids1");

function getData() {
  fetch('all.json')
  .then(response => response.json())
  .then(data => {
    const newVal = myObj.BTCUSDT['bids']['0']['0'];
    bids.innerHTML = newVal
    bids.classList.toggle("green",val > newVal)
    bids.classList.toggle("red",val < newVal)
    val = newVal;
    setTimeout(getData,1000)
  })
}  
getData()