2011-10-14 71 views
1

我想根据单元格的内容设置单元格的背景颜色。JQGrid:如何根据内容设置单元格样式

我的第一个问题:有没有一种方法可以从xml数据中设置单元格的背景颜色?

如果不是,这是我网格的定义:

$("#grid_sites").jqGrid({ 
    url:"getgridxmlsites.php?detailid=" + $('#hdnStudyDetailId').val(), 
    datatype: "local", 
    height: 160, 
    width: 832, 
    shrinkToFit: true, 
    caption:"", 
    colNames :["Site","Name","PI","Location","Phone","Status"], 
    colModel :[ 
     {name:"sitenumber", index:"sitenumber", width:50, align:"right"}, 
     {name:"name",  index:"name",  width:120}, 
     {name:"location",  index:"location", width:100}, 
     {name:"phone",  index:"phone",  width:100}, 
     {name:"status",  index:"status",  width:70} 
    ], 
    pager:"pager_sites", 
    scroll: 1, 
    viewrecords:true, 
    sortable:true, 
    sortname: "sitenumber", 
    autowidth: true, 
    pgbuttons: false, 
    loadonce: true, 
    gridview: true 
}); 

我想改变基于其内容的状态单元格的背景颜色。 我知道我应该在状态栏上使用一个格式化程序,但是我不确定代码只是改变那个单元格的背景颜色。

{name:"status", index:"status", width:70, formatter: statusFormatter} 

function statusFormatter(cellvalue, options, rowObject) 
{ 
    What exactly would go here for something like this: 

    if (cellValue == 'Pending') change the cell's background color to yellow 
    else if (cellValue == 'Approved') change the cells's background color to green; 
} 

谢谢!

回答

1

有很多方法可以做你想做的。在the answer中,您会找到一个示例,了解如何使用自定义格式化程序根据其内容更改单元格的背景颜色。答案写在之前cellattr属性被引入。自定义格式化程序的主要目的是根据单元格的数据创建单元格的HTML包含。

cellattr属性引入的my feature request修改具有优势,因为它仅允许设置/修改属性的小区的HTML代码的,并使用一些预定义的格式,如“数字”或“选择”。因此,您可以只设置classstyle属性并同时使用某些预定义的格式化程序,该格式程序对应于数据包含的内容。查看this answer,其中显示了如何通过classanother answer动态地设置background-color,其中显示了如何通过style进行设置。

The answer另外讨论了这两种方法的优点和缺点。

对您的代码还有一点评论。我不建议您使用url参数的形式

url:"getgridxmlsites.php?detailid=" + $('#hdnStudyDetailId').val() 

它有两个重要的缺点。首先,如果$('#hdnStudyDetailId').val()的内容包含一些特殊字符('','+','=','ä','д','电',),那么$('#hdnStudyDetailId').val()可能会以错误的方式在服务器上发送和解码。 ..)。第二个问题是在创建网格时,'#hdnStudyDetailId'的值只能读取一次。因此,在网格的任何刷新包含像由另一列排序,分页等等将使用来自'#hdnStudyDetailId'元素的相同旧值。我建议你阅读the answer及受尊重的urlpostData参数使用URL:

url: "getgridxmlsites.php", 
postData: { 
    detailid: function() { return $('#hdnStudyDetailId').val(); } 
} 
+0

非常感谢您的回复。我可能会使用loadComplete事件并遍历所有行来设置单元格属性。 –

+0

@David Davis:通过所有行在'loadComplete'内循环的方式总是缓慢,因为cellattr或自定义formater与'gridview:true'参数一起使用,您已经使用它。如果因为任何其他原因决定使用循环,请查看[答案](http://stackoverflow.com/questions/5664587/jqgrid-load-large-data-set-without-pagination/5690583#5690583 ),它描述了相对有效的方法来实现这一点。 – Oleg

+0

再次感谢。我在使用cellattr时再次详细阅读了您的文章,并尝试过并且更喜欢它。现在我知道根据内容格式化单个单元格的正确方法。再次感谢您的帮助。 –

相关问题