Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

jquery - How can I change the background color of a cell in a jqgrid custom formatter?

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).

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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: enter image description here

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...