如何更改jqgrid自定义格式化程序中单元格的背景颜色?

问题描述:

我可以通过在jqgrid自定义格式化程序中执行以下操作来更改文本颜色:

I can change the text color by doing this in jqgrid custom formatter:

function YNFormatter(cellvalue, options, rowObject)
{
    var color = (cellvalue == "Y") ? "green" : "red";
    var cellHtml = "<span style='color:" + color + "' originalValue='" +
                                cellvalue + "'>" + cellvalue + "</span>";

    return cellHtml;
 }

但是我现在想更改整个单元格的背景色(而不是文本颜色).

but I want to now change the background color of the whole cell (instead of the text color).

这可能吗?

如果要在自定义单元格格式化程序中使用<span>元素,则可以从自定义格式化程序返回

If you want use <span> element inside of the custom cell formatter you can return from the custom formatter

return '<span class="cellWithoutBackground" style="background-color:' +
       color + ';">' + cellvalue + '</span>';

您可以定义span.cellWithoutBackground的样式,例如以下

where the style of span.cellWithoutBackground you can define for example like following

span.cellWithoutBackground
{
    display:block;
    background-image:none;
    margin-right:-2px;
    margin-left:-2px;
    height:14px;
    padding:4px;
}

工作原理,您可以在此处观看:

How it works you can see live here:

更新:答案很旧.最佳实践是在colModel中使用cellattr回调,而不是使用自定义格式化程序.通常,仅将styleclass属性分配给该列的单元格(<td>元素),即可更改该单元格的背景颜色.在colModel列中定义的cellattr回调允许完全执行此操作.人们仍然可以使用预定义的格式设置器,例如formatter: "checkbox"formatter: "currency"formatter: "date"等,但是仍然可以更改列中的背景色.可以将rowattr回调定义为jqGrid选项(在colModel的特定列之外),以相同的方式,可以分配整行(<tr>元素)的样式/类.

UPDATED: The answer is old. The best practice would be to use cellattr callback in colModel instead of the usage custom formatters. Changing of background color of the cell is in general just assigning style or class attribute to the cells of the column (<td> elements). The cellattr callback defined in the column of colModel allows exactly to do this. One can still use predefined formatters like formatter: "checkbox", formatter: "currency", formatter: "date" and so on, but still change the background color in the column. In the same way the rowattr callback, which can be defined as the jqGrid option (outside of specific column of colModel), allows to assign style/class of the whole row (<tr> elements).

有关cellattr的更多信息,可以在此处另一个答案解释了rowattr.

More information about cellattr can be found here and here, for example. Another answer explains rowattr.