2

我正在尝试使用 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 - 红色。

4

1 回答 1

2

简单..使用内联函数设置样式

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}"}
]};

或最佳实践是设置类并像这样在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;}
于 2014-09-05T18:04:23.470 回答