我正在创建一个股票小部件。如果Change或Changeinpercent列中的值发生变化,我希望能够将字体颜色设置为红色( - )减少或绿色(+)并增加值。
以下是我到目前为止的内容:http://jsfiddle.net/thetuneupguy/r2Bca/
$(function() {
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.quotes%20WHERE%20symbol%20in(%22GCF14.CMX%22%2C%22SIF14.CMX%22%2C%22PAH14.NYM%22%2C%22PLF14.NYM%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {
console.log("data: ", data);
console.log(data.query.results.quote);
$.each(data.query.results.quote, function(key, obj){
var $tr = $('<tr/>', {'class': 'my-new-list'}).appendTo('#blk-1 table');
$tr.append($('<td/>').text(obj.Name || "--"));
$tr.append($('<td/>').text(obj.Ask || "--"));
$tr.append($('<td/>').text(obj.Bid || "--"));
$tr.append($('<td/>').text(obj.Change || "--"));
$tr.append($('<td/>').text(obj.ChangeinPercent || "--"));
});
});
});
答案 0 :(得分:2)
首先,添加这两条css规则:
.increase{
color:green;
}
.decrease{
color:red;
}
然后,而不是:
$tr.append($('<td/>').text(obj.ChangeinPercent || "--"));
你应该这样做:
var $td = $('<td/>').text(obj.ChangeinPercent || "--");
if(/^\+/.test(obj.ChangeinPercent || '')) $td.addClass("increase"); //If it starts with '+', make it green
if(/^-/.test(obj.ChangeinPercent || '')) $td.addClass("decrease"); //If it starts with '-', make it red
$tr.append($td);
答案 1 :(得分:0)
// Assuming the values will have always a + or -
(obj.Change.substr(0,1) == '+') ? changeClass = 'green' : changeClass = 'red';
(obj.Change.substr(0,1) == '+') ? changeInPercentClass = 'green' : changeInPercentClass = 'red';
$tr.append($('<td class="'+changeClass+'">').text(obj.Change || "--"));
$tr.append($('<td class="'+changeInPercentClass+'">').text(obj.ChangeinPercent || "--"));
我更新了小提琴