我正在尝试读取JSON数据并以绿色或红色打印,具体取决于' scoreChange'大于或小于零。
<script>
$.getJSON('/fetchTicker', function (data) {
$.each(data.result, function () {
$("#marqueecontent").append("<span"
if (this['scoreChange'] >= 0){
"style='color:#66FF13'>" + this['playerName']
+ " + " + this['scoreChange'] + " % " + " ▲ ";
}else(this['scoreChange'] < 0){
"style='color:#FF2020'>" + this['playerName']
+ this['scoreChange'] + " % " + " ▼ ";
}
"❘ </span>"
);
});
});
</script>
答案 0 :(得分:1)
而不是使用if
内部追加。将颜色值指定给它之前的变量。然后在附加中使用它
<script>
$.getJSON('/fetchTicker', function (data) {
$.each(data.result, function () {
var colorToChange = "";
if (this['scoreChange'] >= 0){
colorToChange = "#66FF13";
}
else
{
colorToChange = "#FF2020";
}
$("#marqueecontent").append("<span style='color:"+colorToChange+"'>" + this['playerName']
+ " + " + this['scoreChange'] + " % " + " ▲ ❘ </span>"
);
});
});
</script>
答案 1 :(得分:0)
或者只需创建对象并在以下后面设置css样式:
<script>
var span = $('<span />').html(this['playerName'] + ' + ' + this['scoreChange'] + ' % ▲ ');
if (this['scoreChange'] >= 0) {
span.css('color', '#66FF13');
} else {
span.css('color', '#FF2020');
}
$("#marqueecontent").append(span);
</script>