问题
I searched alot and I'm extremely sure it can be done easily but I cannot find a way to do it. So I use jQuery DataTables and I'm trying to generate a class and do a few javascript action depending on the value I'm recieving. For example, something as simple as putting a red background when the unit is negative, etc. I already created my CSS for this and now I'm loading a JSON file via the ajax parameters of DataTables. Here's my javascript:
table = $('#activitiesTable').DataTable({
"ajax": "data.txt",
"columns": [
{ "data": "id" },
{ "data": "description" },
{ "data": "type_of_expenditure" },
{ "data": "real_cost" }
]
});
I know that in the columns parameters, you can set a class right after by calling the "className" in the json, but I'm not sure how to generate a class by comparing a variable. For example, I'd like to do this:
"columns": [
{
"data" : "id",
"className": (data.id < 0 ? "negative" : "positive"))
}
]
Not sure if this can be done this way? Or if I have to check on jQuery everytime the ajax call is launched but I feel lt could be easily initialized right there...
回答1:
I found that you can use it that way:
{
"data": "forcast_profit_loss",
"createdCell": function (td, cellData, rowData, row, col) {
if ( cellData < 0 ) {
$(td).addClass('number number-negative');
$(td).text(cellData.substr(1));
}
else{
$(td).addClass('number number-positive');
}
}
}
You can find references about it right there: https://datatables.net/reference/option/columns.createdCell
来源:https://stackoverflow.com/questions/30245607/put-a-class-depending-on-the-data-ajax-datatables