简体   繁体   English

如何将 JS JSON 响应红色的负数变为红色?

[英]How to turn negative numbers red from JS JSON response Red?

I am creating a ticker tape for a website and have been able to get all the data I need, however, I can not seem to get the negative change value on the daily price to turn green for up or red for down.我正在为一个网站创建一个自动收报机磁带,并且已经能够获得我需要的所有数据,但是,我似乎无法获得每日价格的负变化值,以向上变为绿色或向下变为红色。 I'm not entirely sure where to start.我不完全确定从哪里开始。 Any help would be greatly appreciated任何帮助将不胜感激

HTML: HTML:

<div id="tickerwrap">
  <marquee>
    <div style="display: inline-block; font-size: 150%">| Apple inc.</div>
    <div style="display: inline-block; font-size: 150%" id=AAPLp></div>
    <div style="display: inline-block; font-size: 150%" id=AAPLchg%></div>
    <div style="display: inline-block; font-size: 150%">| Amazon inc.</div>
  </marquee>
</div>
<script>
document.onreadystatechange = function() {
  if (document.readyState === 'complete') {
    tickertape();
  }
};

JS: JS:

  function tickertape() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var tickertape = JSON.parse(this.responseText);
    document.getElementById("AAPLp").innerHTML = tickertape["AAPL"]["quote"]["latestPrice"];
    document.getElementById("AAPLchg%").innerHTML = tickertape["AAPL"]["quote"]["changePercent"];
    document.getElementById("AAPLchg").innerHTML = tickertape["AAPL"]["quote"]["change"];
    document.getElementById("AMZNp").innerHTML = tickertape["AMZN"]["quote"]["latestPrice"];
    document.getElementById("AMZNchg%").innerHTML = tickertape["AMZN"]["quote"]["changePercent"];
    document.getElementById("AMZNchg").innerHTML = tickertape["AMZN"]["quote"]["change"];
  }
};
xhttp.open("GET", "https://cloud.iexapis.com/v1/stock/market/batch?&types=quote&symbols=aapl,amzn&token=pk_6925213461cb489b8c04a632e18c25dd", true);
xhttp.send();

}; };

Just check the value and set the color.只需检查值并设置颜色。 I'm assuming the values form the JSON are numbers, if not you can use parseFloat() to convert them to numbers:我假设 JSON 的值是数字,如果不是,您可以使用parseFloat()将它们转换为数字:

if (tickertape.AAPL.quote.change < 0) {
    document.getElementById("AAPLchg").style.color = 'red'; // or #f00
}
else {
    document.getElementById("AAPLchg").style.color = 'green'; // or #0f0
}

Alternatively you can use the same logic to add a className and define the colors in CSS.或者,您可以使用相同的逻辑添加 className 并在 CSS 中定义 colors。

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

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