JQuery与HTML混合

时间:2017-09-22 04:21:43

标签: php

我正在尝试读取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'] + " % " + "&nbsp;&#9650;&nbsp;";
        }else(this['scoreChange'] < 0){
          "style='color:#FF2020'>" + this['playerName']
                + this['scoreChange'] + " % " + "&nbsp;&#9660;&nbsp;";  
        }
                "&#x2758;&nbsp;&nbsp;</span>"

                );
    });
});
</script>

2 个答案:

答案 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'] + " % " + "&nbsp;&#9650;&nbsp;&#x2758;&nbsp;&nbsp;</span>"

                );
    });
});
</script>

答案 1 :(得分:0)

或者只需创建对象并在以下后面设置css样式:

<script>
var span = $('<span />').html(this['playerName'] + ' + ' + this['scoreChange'] + ' % &nbsp;&#9650;&nbsp;');

if (this['scoreChange'] >= 0) {
    span.css('color', '#66FF13');
} else {
    span.css('color', '#FF2020');
}

$("#marqueecontent").append(span);
</script>