我正在创建一个股票小部件。如果“更改”或“更改百分比”列中的值发生更改,我希望能够将字体颜色设置为红色,以表示(-)减小值;或将绿色设置为(+)并增大值。

到目前为止,这是我得到的: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 || "--"));
        });

    });
});

最佳答案

// 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 || "--"));


我更新了小提琴

http://jsfiddle.net/r2Bca/4/

10-07 14:21