将 'positive' 样式应用到百分比(如果为正)- 从 Google 工作表中提取

Apply 'positive' style to a percentage if positive - pulled from Google Sheets

我使用 ID 从 Google 工作表中提取数据(包括数字和百分比)。我正在尝试使用 Javascript 应用样式,如果数据为正则将数据着色为绿色,如果数据为负则为红色。我的 Javascript 工作非常适合数字,但不适合百分比。

代码笔:https://codepen.io/liamdthompson/pen/YbQRgv

    divs.forEach(function(div){
        // Convert text to number and test for positive/negative
        if((+div.textContent) >= 0){
        div.classList.add("positive"); // Apply positive style
        } else {
        div.classList.add("negative"); // Apply negative style  
        }
    });  
    });
.positive {
  color: green;
}
.negative {
  color: red;
}

目前这导致数字“10.2”显示为绿色,但百分比“2.00%”显示为黑色(样式不起作用)。

您可以添加一个额外的条件来检查 % 是否存在于即将到来的值中,然后相应地处理它。

         if(div.textContent.includes('%')){
              div.textContent = div.textContent.split('%')[0];
            }

检查更新的代码段

.positive {
  color: green;
}
<div class="" id="QStreak"></div>
<div id="QStreak1"></div>

<!--JavaScript at end of body for optimized loading-->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
  <script type="text/javascript">
      
 


  function httpGetAsync(theUrl, callback)  {

  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", theUrl, true); // true for asynchronous
  xmlHttp.send(null);
  
  }


  httpGetAsync ('https://spreadsheet.glitch.me/?key=1mT_ILqpPtoCnWq5fEcBbVcgkKxcXN6uS9F2fsAO7imI', function(response) {
  var json = JSON.parse(response);

 //QStreak
      document.getElementById("QStreak").innerHTML = json[6].ThisWeek;
  document.getElementById("QStreak1").innerHTML = json[6].PriceChange;
 
  let divs = Array.prototype.slice.call(document.querySelectorAll("#QStreak, #QStreak1"));



  // Loop the array
    divs.forEach(function(div){
        // Convert text to number and test for positive/negative
        let num = div.textContent;
        if(div.textContent.includes('%')){
           
          div.textContent = div.textContent.split('%')[0];
        }
      
        if((+div.textContent) >= 0){
        div.classList.add("positive"); // Apply positive style
        } else {
        div.classList.add("negative"); // Apply negative style  
        }
        div.textContent = num;
    });  
    });

  
  </script>