项目中使用到了插件datatables,实在太强大了,有了这样的需求,需要根据数据来显示是否要更换背景,以便区别对待,datatables里面有一个属性是: aocolumndefs,里面可以获取到每行的一行json数据,然后设置背景,返回即可.如下:
//设置某些列为特定样式
"aoColumnDefs" : [
{"aTargets": [0], mRender: function (data, type, c, d) {
alert("类型为:"+type);
alert("渲染类型:"+d);
// alert(c.lastPersonWage.wage.positionRankWage);
// alert(c.currentPersonWage.wage.positionRankWage);
var lastM =c.lastPersonWage.wage.positionRankWage;
var currentM = c.currentPersonWage.wage.positionRankWage;
if(lastM != currentM){
alert("两者不相等");
return data ="<span class='cos_class'>测试更改某个单元格</span>";
//return c.lastPersonWage.wage.positionRankWage;
}
return c.currentPersonWage.retirementCardNo;
}},
// {
// "sClass" : "cos_class",
// "aTargets" : [ 3 ]
// }
],
参考博客:http://blog.csdn.net/qq_30259339/article/details/51151552,解释一下 render:
function(a, b, c, d) {}:
ajax表示请求的地址,columns要和返回的json数据中的字段对应,并和table中的th对应
"serverSide": true, //启用服务模式这个表示后台分页
aoColumns[]数组中表示后端返回的json数据(也和table中的th的数量一致,所以这块容易出错),mData表示json对象的属性名,orderable是否启动排序,sDefaultContent没有这个属性的情况下的默认值,sWidth表示th的宽度,render方法表示对接收到的json数据进行处理判断后显示,` "render" : function(data, type, full, meta) {
//return data == 1 ? '有效' : '<font color="red">无效</font>';
if(data==1){
data ="<a href='#' class='upOrderStatus' data-id="+full.id+">有效</a>";
}else{
data ="<a href='#' class='upOrderStatus' data-id="+full.id+"><font color='red'>无效</font></a>";
}
return data;
}`
data表示该json属性的值,type不清楚,full表示整个json对象,就是一整行的值,d不清楚,对data进行处理,再渲染
注:设置背景的class样式为:
.cos_class {
color: #FFA500;
}
最终效果如图:
2.给datatables的某行某列添加点击事件:
$('#sample_1 tbody').on('click','tr:nth-child(2) td:nth-child(2)', function (e) {
var name = $(this).text();
alert("给第2行第2列的JQuery datatables添加点击事件"+name);
} );