How can I apply differnt styles when transforming

2019-07-11 04:37发布

I am trying to format data using json2html

data is as follows:

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

transform is as follows:

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

but I need the background color of the div above to be colored based on level, as an example level 1 - yellow, level 2 - green, level 3 - red.

标签: json2html
1条回答
男人必须洒脱
2楼-- · 2019-07-11 05:23

simple .. use an inline function to set the style

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 best practice would be to set the class and apply the style in css like so

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;}
查看更多
登录 后发表回答