如何动态更改单元格格式

nat*_*ath 0 javascript css dojo dojox.grid dojox.grid.datagrid

我使用dojo实现了一个datagrid,每5秒更新一次.我使用以下代码来更新datagrid.

jsonStore.fetch({
         query: {id:'*'},
         onComplete: function(items, result){
         dojo.forEach(items, function(item){
             jsonStore.setValue(item, "time" , data.update[0].netchange);
.....
Run Code Online (Sandbox Code Playgroud)

'data'是我需要设置到网格的新数据,它是一个json对象,如下所示

var data = {"update":[{...}]}
Run Code Online (Sandbox Code Playgroud)

如果netchage为负,我需要做什么我需要将单元格颜色设置为红色.如果netchange是积极的,它应该是绿色的.所以我需要一种动态更改单元格格式的方法.有人可以告诉我这是怎么回事.提前致谢

grid4 = new dojox.grid.DataGrid({
            query : {
                Title : '*'
            },
            id : "grid",
            jsId : "grid",
            clientSort : true,
            rowSelector : '0px',
            structure : layout4
        }, document.createElement('div'));
        grid4.setStore(jsonStore);
        dojo.byId("gridContainer4").appendChild(grid4.domNode);

var layout4 = [ {
            field : 'time',
            name : 'time',
            width : '40px',
            formatter: geticon()
        }, {
            field : 'netchange',
            name : 'netchange',
            width : '30px'
        } ];
Run Code Online (Sandbox Code Playgroud)

Lay*_*yke 5

在我回答这个问题之前,当你说"动态更改单元格格式"时,只是一个微不足道的误称.

您没有更改单元格formatter,而是更改单元格的样式.

每次将值加载到单元格中时,都会调用格式化程序.此外,为单元格所在的行调用onStyleROw函数.

这意味着您有两个选项可以更改单元格的颜色.您可以在单元格范围内执行此操作,或者您可以让格式化程序执行一些简单的操作,例如使用<span>具有不同样式颜色的值来包装值.我会告诉你们两个.

这是第一个不改变任何现有网格代码的解决方案,它将使用onStyleRow更改整行.

解决方案1使用onStyleRow

步骤1.(连接onStyleRow)

dojo.connect(grid4,"onStyleRow",styleRowGridPayment);

第2步.(创建styleRowGridPayment方法.)

var styleGridPayment = function(inRow) {
        if( null !== grid4.getItem( inRow.index ) ) {
            item = grid4.getItem( inRow.index );
            if( item.netchange < 0 ) {
                inRow.customStyles += "color:red;";
            } else {
                inRow.customStyles += "color:green;";
            }
         }
    }   
Run Code Online (Sandbox Code Playgroud)

这应该用于使用onStyleRow.

解决方案2,使用格式化程序

在你的现场声明中,你会有

{
    field : 'netchange',
    name : 'netchange',
    width : '30px'
    formatter: formatNetchange
} 
Run Code Online (Sandbox Code Playgroud)

请注意,我已将formatNetchange添加为格式化程序.

然后你只需创建格式化程序.

formatNetchange = function(value){
     if(value < 0){
        color = "red";
     } else {
        color = "green";
     }
     return "<span style='color:" + color "'>" + value "</span>";
}
Run Code Online (Sandbox Code Playgroud)