gpt4 book ai didi

javascript - 将 'positive' 样式应用于百分比(如果为正)- 从 Google 表格中提取

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:39 25 4
gpt4 key购买 nike

我使用 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>

关于javascript - 将 'positive' 样式应用于百分比(如果为正)- 从 Google 表格中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com