Layui数据表格设置选中行背景及字体颜色

话不多说直接上代码:

  1 $(function () {
  2     var countNum = 0;
  3     var t;
  4     layui.use(['form', 'table'], function () {
  5         var table = layui.table;
  6         var form = layui.form;
  7 
  8 
  9         form.on('submit(exportData)', function (data) {
 10 
 11             $.ajax({
 12                 type: 'POST',
 13                 url: 'handler/ExportHandler.ashx?flag=6',
 14                 data: { cyc: data.field.cyc, zyq: data.field.quiz1, qk: data.field.quiz2, jh: data.field.jh, ny: ny },
 15                 success: function (date) {
 16                     console.log("success");
 17                     $("#downloadRul").attr("href", date);
 18                     $('#downloadRul>p').trigger("click");
 19 
 20                 },
 21                 //                            dataType: "json"
 22             });
 23             //window.location = "ExportHandler.ashx";
 24 
 25             return false;
 26         });
 27    table.render({
 28         id:'jh',
 29         elem: '#jhList'
 30         , height: 'full-200'
 31         , url: 'handler/WellList.ashx' //数据接口
 32         , cellMinWidth: '20'
 33         , page: false //开启分页
 34         , limits: [150, 300, 450]
 35         ,even:true
 36         , cols: [[
 37           { field: 'JH1', title: '预警', '90',align: 'center'},
 38           { field: 'jh1', title: '传输状态',  '90', align: 'center' },
 39           { field: 'jhbm', title: '井名',  '100', align: 'center'},
 40           { field: 'yidcount', title: '段数',  '95', align: 'center'},
 41           { field: 'jh', title: 'id', align: 'center', style: 'display:none;'}
 42         ]]
 43        , done: function (res, curr, count) {
 44            $('table.layui-table thead tr th:eq(4)').addClass('layui-hide');
 45            countNum = res.data.length;
 46            $('th').css({ 'background-color': '#BCD2EE', 'color': 'black' });//设置th颜色
 47            //tr隔行换色
 48            var that = this.elem.next();
 49            res.data.forEach(function (item, index) {
 50                
 51                if (index % 2 == 0) {
 52                    var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", '#D1EEEE');
 53                } else {
 54                    var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", 'white');
 55                }
 56                if (index == 0) {
 57                    //默认选中行
 58                    var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", '#1E9FFF');
 59                    var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("color", '#fff');
 60                    var jh = item["jh"];
 61                    //chart(jh, item["jhbm"]);//打开窗体默认加载曲线
 62                    t = setInterval(function () { chart(jh, item["jhbm"]) }, 1000);//执行定时方法chart("","")
 63                }
 64            })
 65            $('td').css({ 'border': 'none' });//设置td无边框
 66            $('th').css({ 'border': 'none' });//设置th无边框
 67            $('td').css({ 'cursor': 'pointer' });//设置th无边框
 68            $('.layui-table-body').find('td').each(function (index, element) {
 69                // console.log('渲染111111'); //得到被选中的值
 70                if ($(this).attr('data-field') >= 0) {
 71                    $(this).css('display', 'none');
 72                }
 73 
 74            });
 75        }
 76    });
 77 
 78    //选中行后改变行背景及字体颜色
 79    $("body").on('click', '.layui-table-body tr ', function () {
 80        console.log(this);
 81        var data_index = $(this).attr('data-index');//得到当前的tr的index
 82        console.log($(this).attr('data-index'));
 83        for (var i = 0 ; i < countNum; i++)//countNum为总行数
 84        {
 85            if (i % 2 == 0) { //设置隔行换色
 86                $(".layui-table-body tr[data-index=" + i + "]").attr({ "style": "background:#D1EEEE;color:black" });//恢复原有tr颜色
 87            } else {
 88                $(".layui-table-body tr[data-index=" + i + "]").attr({ "style": "background:#fff;color:black" });//恢复原有tr颜色
 89            }
 90        }
 91        $(".layui-table-body tr[data-index=" + data_index + "]").attr({ "style": "background:#1E9FFF;color:#fff" });//改变当前tr颜色
 92 
 93    });
 94 
 95    //单击行的监听事件
 96    table.on('row(jhList)', function (obj) {
 97        var jh = obj.data.jh;
 98        var jhbm = obj.data.jhbm;
 99        window.clearInterval(t);
100        t = setInterval(function () { chart(jh, jhbm) }, 1000);
101        //chart(jh, jhbm);
102    });
103 });
104 });

最主要的部分:

//选中行后改变行背景及字体颜色
   $("body").on('click', '.layui-table-body tr ', function () {
       console.log(this);
       var data_index = $(this).attr('data-index');//得到当前的tr的index
       console.log($(this).attr('data-index'));
       for (var i = 0 ; i < countNum; i++)//countNum为总行数
       {
           if (i % 2 == 0) { //设置隔行换色
               $(".layui-table-body tr[data-index=" + i + "]").attr({ "style": "background:#D1EEEE;color:black" });//恢复原有tr颜色
           } else {
               $(".layui-table-body tr[data-index=" + i + "]").attr({ "style": "background:#fff;color:black" });//恢复原有tr颜色
           }
       }
       $(".layui-table-body tr[data-index=" + data_index + "]").attr({ "style": "background:#1E9FFF;color:#fff" });//改变当前tr颜色

   });

  

如果数据表格不设置间隔换色的话还可以这样:

 //选中行后改变行背景及字体颜色
        $("body").on('click', '.layui-table-body tr ', function () {
            console.log(this);
            var data_index = $(this).attr('data-index');//得到当前的tr的index
            console.log($(this).attr('data-index'));
            $(".layui-table-body tr").attr({ "style": "background:#FFFFFF; color:#666666" });//其他tr恢复颜色
            $(".layui-table-body tr[data-index=" + data_index + "]").attr({ "style": "background:#F2F2F2;color:#666666" });//改变当前tr颜色

        });

将整个数据表格的行都设置为相同背景及字体,再将选中的行设置想要的背景及字体,这样更简单。

当然还有一种情况就是当一个页面使用到两个或两个以上数据表格的时候以上方法就会出现问题,但选择其中一个表格时,其他表格也会跟着一起改变,他们所有的class都相同所以就会冲突,只有 lay-id 属性是不同的,所以就要借助这个来定位到没有个数据表格的每行每列及每个单元格,如下代码给数据表格行添加触发事件,其中JHNUM为数据表格数据的总数量,当选中某一行时把所有的行都恢复到初始颜色,再改变当前选中行的背景及字体颜色,通过$("[lay-id='jhList'] tbody tr[data-index=" + i + "]")定位到是当前我点击的这个ID为jhList的数据表格。这样就可以达到一个页面有多个数据表格可以分边改变背景颜色及字体。

 1    table.on('row(jhList)', function (obj) {
 2        //隔行换色,显示当前行
 3        for (var i = 0 ; i < JHNUM; i++)//countNum为总行数
 4        {
 5            if (i % 2 == 0) { //设置隔行换色
 6                $("[lay-id='jhList'] tbody tr[data-index=" + i + "]").attr({ "style": "background:#D1EEEE;color:#666666" });//恢复原有tr颜色
 7            } else {
 8                $("[lay-id='jhList'] tbody tr[data-index=" + i + "]").attr({ "style": "background:#fff;color:#666666" });//恢复原有tr颜色
 9            }
10        }
11        $(this).attr({ "style": "background-color:#1E9FFF;color:#ffffff" });
12 
13    });
原文地址:https://www.cnblogs.com/xiong950413/p/13304248.html