How can I apply differnt styles when transforming data using json2html based on data value?

北慕城南 提交于 2019-12-24 03:14:49

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/25660023/how-can-i-apply-differnt-styles-when-transforming-data-using-json2html-based-on

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!