在基于数据值使用json2html转换数据时,如何应用不同的样式? [英] How can I apply differnt styles when transforming data using json2html based on data value?

查看:197
本文介绍了在基于数据值使用json2html转换数据时,如何应用不同的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to format data using 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-红色.

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.

推荐答案

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

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

或最佳做法是像这样设置类并在CSS中应用样式

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

这篇关于在基于数据值使用json2html转换数据时,如何应用不同的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆