Datatables展示数据(表格合并、日期计算、异步加载数据、分页显示、筛选过滤)

简介: Datatables展示数据(表格合并、日期计算、异步加载数据、分页显示、筛选过滤)

前言


Datatables是一款jquery表格插件,jquery表格插件是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。


分页,即时搜索和排序

几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理

支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation

各式各样的扩展: Editor, TableTools, FixedColumns

丰富多样的option和强大的API

超过2900+个单元测试

免费开源


一、html容器构建

1.操作按钮

<!--操作按钮-->
<div class="btn-group">
    <button id="reload" class="searchBtn progress">刷新</button>
    <button id="all" class="searchBtn all">全部</button>
    <button id="total" class="searchBtn all">总量</button>
<!--    <button id="progress" class="searchBtn stopped">A相电流</button>
    <button id="alerted" class="searchBtn stopped">B相电流</button>
    <button id="closed" class="searchBtn stopped">C相电流</button>-->
</div>


2.表格构建

<table id="example" class="display panel" role="grid" aria-describedby="example_info">
    <thead>
    <tr align="center">
        <td></td>
        <td></td>
        <td colspan="6" class="tablebg2">月电量 <span style="color: #e60000;font-size: 10px;">Kwh</span></td>
        <td colspan="3" class="tablebg1">年电量 <span style="color: #e60000;font-size: 10px;">Kwh</span></td>
        <td colspan="3" class="tablebg2">电流  <span style="color: #e60000;font-size: 10px;">A</span></td>
        <td class="tablebg1">功率  <span style="color: #e60000;font-size: 10px;">W</span></td>
    </tr>
    <tr align="center">
        <td>序号</td>
        <td>位置</td>
        <td class="tablebg2">{'0'|getPowerDate:'0'}</td>
        <td class="tablebg2">{'0'|getPowerDate:'-1'}</td>
        <td class="tablebg2">{'0'|getPowerDate:'-2'}</td>
        <td class="tablebg2">{'0'|getPowerDate:'-3'}</td>
        <td class="tablebg2">{'0'|getPowerDate:'-4'}</td>
        <td class="tablebg2">{'0'|getPowerDate:'-5'}</td>
        <td class="tablebg1">{'1'|getPowerDate:'0'}</td>
        <td class="tablebg1">{'1'|getPowerDate:'-1'}</td>
        <td class="tablebg1">{'1'|getPowerDate:'-2'}</td>
        <td class="tablebg2">A相电流</td>
        <td class="tablebg2">B相电流</td>
        <td class="tablebg2">C相电流</td>
        <td class="tablebg1">电功率</td>
    </tr>
    </thead>
    <tbody></tbody>
</table>


二、时间日期计算

/*时间表头
 * $type 0月份1年份;
 * $inter 时间间隔
*/
function getPowerDate($type, $inter)
{
    //返回月份
    if ($type == 0) {
        return date("Y-m", strtotime("" . $inter . " month"));
    }
    //返回年份
    if ($type == 1) {
        return date("Y", strtotime("" . $inter . " year"));
    }
}


三、dataTables属性配置

1.调用

使用DataTables很简单,只需要引入两个文件, 一个css样式文件和DataTables本身的脚本文件。

    <link rel="stylesheet" href="css/jquery.dataTables.css">
    <script type="text/javascript" src="js/jquery.dataTables.js"></script>


2.过滤按钮

//重载页面;
        $("#reload").click(function () {
            window.location.href = window.location.href;
        })
        $('#all').on('click', function () {
            $('.dataTables_filter [type=search]').val("").keyup();
        });
        $('#progress').on('click', function () {
            $('.dataTables_filter [type=search]').val("A相电流").keyup();
        });
        $('#alerted').on('click', function () {
            $('.dataTables_filter [type=search]').val("A相电流").keyup();
        });
        $('#closed').on('click', function () {
            $('.dataTables_filter [type=search]').val("C相电流").keyup();
        });
        $('#total').on('click', function () {
            $('.dataTables_filter [type=search]').val("总量").keyup();
        });


3.异步加载数据

    $.ajax({
        type: 'get',
        async: true,
        data: {},
        url: 'api/api.php?act=getIotPower&token=3cab7ce4142608c0f40c785b5ab5ca24',
        dataType: "json",
        success: function (res) {
        //核心代码
        } else {
              //无数据判断
            }
        },
        error: function (err) {
            console.log(err);
        }


4.核心代码

DataTable属性配置

$('#example').DataTable({
                    dom: '<"searchBox"lf>t<"dtPage"i>p',//控件位置
                    bFilter: true,//过滤搜索
                    pagingType: "first_last_numbers",//分页样式
                    pageLength: 15,//默认显示条数;
                    bPaginate: true,//分页总开关
                    lengthMenu: [15, 25, 50, 75, 100, 200],
                    language: {
                        emptyTable: '没有数据',
                        loadingRecords: '加载中...',
                        processing: '查询中...',
                        search: '搜索:',
                        lengthMenu: '每页 _MENU_ 条数据',
                        zeroRecords: '没有数据',
                        paginate: {
                            'first': '首页',
                            'last': '尾页',
                            'next': '下一页',
                            'previous': '上一页'
                        },
                        info: '共计:_TOTAL_ 条数据',
                        infoEmpty: '没有数据',
                        infoFiltered: '(过滤 _MAX_ 条)',
                    }
                });


数据运算

var json = res.data;
            //console.log(json);
            var html = '';
            if (res.data != null) {
                for (var i = 0; i < json.length; i++) {
                    var sensor = json[i].data.propertyType;
                    var b_yesterday_val = json[i].odata.b_yesterday_val.split(",");
                    var yesterday_val = json[i].odata.yesterday_val.split(",");
                    var last_month_val = json[i].odata.last_month_val.split(",");//1月
                    var b_last_month_val = json[i].odata.b_last_month_val.split(",");//2月
                    var last_year_val = json[i].odata.last_year_val.split(",");
                    var b_last_year_val = json[i].odata.b_last_year_val.split(",");
                    var three_days_ago_val = json[i].odata.three_days_ago_val.split(",");
                    var three_month_ago_val = json[i].odata.three_month_ago_val.split(",");//3月
                    var three_years_ago_val = json[i].odata.three_years_ago_val.split(",");
                    var four_month_ago_val = json[i].odata.four_month_ago_val.split(",");//4月
                    var five_month_ago_val = json[i].odata.five_month_ago_val.split(",");//5月
                    var six_month_ago_val = json[i].odata.six_month_ago_val.split(",");//6月
                    var normValue = json[i].sdata.split(",");
                    var sta = json[i].data.sensorStatus;
                    var norm = sensor.split(",");
                    var staValue = sta.split(",");
                    //新增当日/月/年数据 2022.07.23 BY poleung;
                    var today_val = json[i].odata.today_val.split(",");
                    var current_month = json[i].odata.current_month.split(",");//当月
                    var current_year = json[i].odata.current_year.split(",");
                    //console.log(today_val);
                    //数据排序,防止错乱;
                    var normT = [], statusT = [], b_yesterday = [], yesterday = [], b_last_month = [], last_month = [],four_month = [],five_month = [],six_month = [],
                        b_last_year = [], last_year = [];
                    for (var j = 0; j < norm.length; j++) {
                        //日用量
                        if (norm.indexOf("电量") == -1) {
                            normT[0] = "-";
                            statusT[0] = "无设备";
                        } else {
                            if (norm[j] == "电量") {
                                //normT[0] = parseFloat(normValue[j] - yesterday_val[j]).toFixed(2);
                                normT[0] = getPositive(parseFloat(today_val[j] - yesterday_val[j]).toFixed(2));//今天
                                statusT[0] = staValue[j];
                                yesterday[0] = getPositive(parseFloat(yesterday_val[j] - b_yesterday_val[j]).toFixed(2));
                                b_yesterday[0] = getPositive(parseFloat(b_yesterday_val[j] - three_days_ago_val[j]).toFixed(2));
                            }
                        }
                        //月用量
                        if (norm.indexOf("电量") == -1) {
                            normT[1] = "-";
                            statusT[1] = "无设备";
                        } else {
                            if (norm[j] == "电量") {
                                statusT[1] = staValue[j];
                                normT[1] = getPositive(parseFloat(current_month[j] - last_month_val[j]).toFixed(2));//1
                                last_month[1] = getPositive(parseFloat(last_month_val[j] - b_last_month_val[j]).toFixed(2));//2
                                b_last_month[1] = getPositive(parseFloat(b_last_month_val[j] - three_month_ago_val[j]).toFixed(2));//3
                                four_month[1] = getPositive(parseFloat(three_month_ago_val[j] - four_month_ago_val[j]).toFixed(2));//4
                                five_month[1] = getPositive(parseFloat(four_month_ago_val[j] - five_month_ago_val[j]).toFixed(2));//5
                                six_month[1] = getPositive(parseFloat(five_month_ago_val[j] - six_month_ago_val[j]).toFixed(2));//6
                            }
                        }
                        //年用量
                        if (norm.indexOf("电量") == -1) {
                            normT[2] = "-";
                            statusT[2] = "无设备";
                        } else {
                            if (norm[j] == "电量") {
                                normT[2] = getPositive(parseFloat(current_year[j] - last_year_val[j]).toFixed(2));
                                statusT[2] = staValue[j];
                                last_year[2] = getPositive(parseFloat(last_year_val[j] - b_last_year_val[j]).toFixed(2));
                                b_last_year[2] = getPositive(parseFloat(b_last_year_val[j] - three_years_ago_val[j]).toFixed(2));
                            }
                        }
                        if (norm.indexOf("A相电流") == -1) {
                            normT[3] = "-";
                            statusT[3] = "无设备";
                        } else {
                            if (norm[j] == "A相电流") {
                                normT[3] = parseFloat(today_val[j]).toFixed(2);
                                statusT[3] = staValue[j];
                            }
                        }
                        if (norm.indexOf("B相电流") == -1) {
                            normT[4] = "-";
                            statusT[4] = "无设备";
                        } else {
                            if (norm[j] == "B相电流") {
                                normT[4] = parseFloat(today_val[j]).toFixed(2);
                                statusT[4] = staValue[j];
                            }
                        }
                        if (norm.indexOf("C相电流") == -1) {
                            normT[5] = "-";
                            statusT[5] = "无设备";
                        } else {
                            if (norm[j] == "C相电流") {
                                normT[5] = parseFloat(today_val[j]).toFixed(2);
                                statusT[5] = staValue[j];
                            }
                        }
                        if (norm.indexOf("电功率") == -1) {
                            normT[6] = "-";
                            statusT[6] = "无设备";
                        } else {
                            if (norm[j] == "电功率") {
                                normT[6] = parseFloat(today_val[j]).toFixed(2);
                                statusT[6] = staValue[j];
                            }
                        }
                    }
                    //构建表格;
                    html = "<tr><td>" + json[i].device_seq + "</td><td>"
                        + json[i].device + "</td><td class=\"tablebg1\">"
                        + normT[1] + "</td><td class=\"tablebg2\">"
                        + last_month[1] + "</td><td class=\"tablebg1\">"
                        + b_last_month[1] + "</td><td class=\"tablebg2\">"
                        + four_month[1] + "</td><td class=\"tablebg1\">"
                        + five_month[1] + "</td><td class=\"tablebg2\">"
                        + six_month[1] + "</td><td class=\"tablebg1\">"
                        + normT[2] + "</td><td class=\"tablebg1\">"
                        + last_year[2] + "</td><td class=\"tablebg1\">"
                        + b_last_year[2] + "</td><td>"+makeBold(normT[3],statusT[3])+"</td><td>"+makeBold(normT[4],statusT[4])+"</td><td>"+makeBold(normT[5],statusT[5])+"</td><td class=\"tablebg1\">"+makeBold(normT[6],statusT[6])+"</td></tr>";
                    //渲染表格;
                    $("#example tbody").append(html);
                }


总结

Datatables是一直接触的jquery表格插件,但仅限于项目部分功能的使用,因此对该插件也是用到时学习,满足了当前的需求就浅尝辄止了。但是随着同一个项目需求的不断变化,反正Datatables带来的惊喜:只有你没想到的功能,没有它实现不了的需求。因而为此记!

@漏刻有时

相关文章
Datatables获取选中行的某一列的数据
Datatables获取选中行的某一列的数据
717 1
Failed to execute script ‘xxx‘ due to unhandled exception:No module named ‘ctypes‘
Failed to execute script ‘xxx‘ due to unhandled exception:No module named ‘ctypes‘
714 0
|
6月前
|
前端开发 数据可视化 BI
3个小时,从学到做,我用低代码平台搭了一套管理系统
本文介绍了如何利用低代码平台快速搭建一套项目管理系统,解决团队在项目进度、任务分配和资源管理上的难题。结合亲身实践,详细展示了从需求分析、系统设计到低代码实现的全过程,并解析了低代码平台的核心本质,帮助读者深入理解其在企业数字化转型中的价值与应用方式。
|
12月前
|
人工智能 移动开发 前端开发
WeaveFox:蚂蚁集团推出 AI 前端智能研发平台,能够根据设计图直接生成源代码,支持多种客户端和技术栈
蚂蚁团队推出的AI前端研发平台WeaveFox,能够根据设计图直接生成前端源代码,支持多种应用类型和技术栈,提升开发效率和质量。本文将详细介绍WeaveFox的功能、技术原理及应用场景。
6253 68
WeaveFox:蚂蚁集团推出 AI 前端智能研发平台,能够根据设计图直接生成源代码,支持多种客户端和技术栈
|
10月前
|
安全 Linux
CentOS下载ISO镜像的方法
访问CentOS官方网站(https://www.centos.org/download/),在“Downloads”页面找到ISO镜像下载链接,选择所需版本和架构(如x86_64)开始下载。CentOS分为Linux版和Stream版,前者每两年发行一次并提供10年安全维护,后者为滚动更新。旧版本可在Vault(https://vault.centos.org/)下载。建议选择DVD格式镜像,包含完整系统和常用软件。
11098 14
CentOS下载ISO镜像的方法
|
SQL 数据库
SQL INSERT INTO SELECT 语句
SQL INSERT INTO SELECT 语句
2790 8
|
9月前
|
中间件 Linux vr&ar
Centos7升级Glibc
centos7升级glic问题
2257 0
|
JavaScript
基于Vue2或Vue3实现任意上下左右拖拽悬浮的元素,且配置为自定义的全局指令
这篇文章介绍了如何在Vue 2或Vue 3项目中实现一个自定义的全局指令`v-dragSwitch`,用于创建可以任意方向拖拽并悬浮的元素,同时包含边界处理的逻辑。
3982 2
基于Vue2或Vue3实现任意上下左右拖拽悬浮的元素,且配置为自定义的全局指令
|
开发框架 前端开发 JavaScript
基于SqlSugar的开发框架循序渐进介绍(5)-- 在服务层使用接口注入方式实现IOC控制反转
基于SqlSugar的开发框架循序渐进介绍(5)-- 在服务层使用接口注入方式实现IOC控制反转
|
SQL NoSQL Shell
03 MongoDB文档的各种增加、更新、删除操作总结
文章总结了MongoDB中文档的增删改操作,包括插入文档、更新现有文档以及删除文档的具体方法和示例。
1012 0