2011-10-14 70 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時再次詳細閱讀了您的文章,並嘗試過並且更喜歡它。現在我知道根據內容格式化單個單元格的正確方法。再次感謝您的幫助。 –

相關問題