在使用基于数据值的json2html转换数据时,如何应用不同的样式?

时间:2014-09-04 07:51:18

标签: json2html

我正在尝试使用json2html格式化数据

数据如下:

            var data = [
                {'name':'Bob','level':1},
                {'name':'Frank','level':2},
                {'name':'Bill','level':3},
                {'name':'Robert','level':1},
                {'name':'Chen','level':3},
                {'name':'Will','level':2}
            ];

变换如下:

var transform = {"tag":"div","class":"player","children":[
                {"tag":"div","class":"p-name","html":"${name}"},
                {"tag":"div","style":"background:yellow","class":"p-level","html":"${level}"}
]}

但是我需要上面div的背景颜色根据级别进行着色,例如1级 - 黄色,2级 - 绿色,3级 - 红色。

1 个答案:

答案 0 :(得分:2)

simple ..使用内联函数设置样式

var transform = {"tag":"div","class":"player","children":[
            {"tag":"div","class":"p-name","html":"${name}"},
            {"tag":"div","style":function(){

                 var color;

                 switch(this.level) {
                   case 1: color = 'yellow';
                   case 2: color = 'green';
                   case 3: color = 'red';
                 };

                 return('background-color:' + color);

            },"class":"p-level","html":"${level}"}
]};

OR最佳实践是设置类并在css中应用样式,如此

var transform = {"tag":"div","class":"player","children":[
            {"tag":"div","class":"p-name","html":"${name}"},
            {"tag":"div","class":"p-level color-level-${level}","html":"${level}"}
]};

.color-level-1 {background-color:yellow;}
.color-level-2 {background-color:green;}
.color-level-3 {background-color:red;}