我试图用javascript实现一种可以检测和着色不同价值的机制 (正面=绿色,负面=红色)。数据来自API(https://api.coinmarketcap.com/v1/ticker/)
我现在遇到的问题: 数据的颜色没有变化。
使用Javascript:
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "ethereum") {
$("#percent_change_1h").html(data[i].percent_change_1h + "%");
$("#percent_change_24h").html(data[i].percent_change_24h + "%");
$("#percent_change_7d").html(data[i].percent_change_7d + "%");
{
if ((data[i].percent_change_7d) < 0) {
$('.percent_change').addClass("negative");
} else if ((data[i].percent_change_7d) > 0) {
$('.percent_change').addClass("positive");
}
};
}
});
HTML:
<table class="percent_change">
<tr>
<td>1hr </td>
<td>24hr</td>
<td>7days</td>
</tr>
<tr>
<td id="percent_change_1h"></td>
<td id="percent_change_24h"></td>
<td id="percent_change_7d"></td>
</tr>
CSS:
.positive {
color:green;
}
.negative {
color:red;
}
有什么建议吗?
答案 0 :(得分:1)
这应该照顾它:
function show(eth) {
$("#eth td").each(function(i, el) {
let num = eth[this.id];
if (num < 0) $(this).addClass("negative");
if (num > 0) $(this).addClass("positive");
$(this).html(num + "%");
});
}
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "ethereum") show(data[i]);
}
});
&#13;
.positive {
color: green;
}
.negative {
color: red;
}
td {
padding: 0.2em
}
&#13;
<script src="//code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<table class="percent_change">
<tr>
<td>1hr </td>
<td>24hr</td>
<td>7days</td>
</tr>
<tr id="eth">
<td id="percent_change_1h"></td>
<td id="percent_change_24h"></td>
<td id="percent_change_7d"></td>
</tr>
</table>
&#13;
答案 1 :(得分:1)
你有一个额外的开放式大括号:
{
^ if ((data[i].percent_change_7d) < 0) {
要应用样式,请使用:
if ((data[i].percent_change_7d) < 0) {
$('#percent_change_7d').addClass("negative");
} else if ((data[i].percent_change_7d) > 0) {
$('#percent_change_7d').addClass("positive");
}
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "ethereum") {
$("#percent_change_1h").html(data[i].percent_change_1h + "%");
$("#percent_change_24h").html(data[i].percent_change_24h + "%");
$("#percent_change_7d").html(data[i].percent_change_7d + "%");
if ((data[i].percent_change_7d) < 0) {
$('#percent_change_7d').addClass("negative");
} else if ((data[i].percent_change_7d) > 0) {
$('#percent_change_7d').addClass("positive");
}
};
}
});
.positive {
color: green;
}
.negative {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="percent_change">
<tr>
<td>1hr </td>
<td>24hr</td>
<td>7days</td>
</tr>
<tr>
<td id="percent_change_1h"></td>
<td id="percent_change_24h"></td>
<td id="percent_change_7d"></td>
</tr>
</table>