侧边栏壁纸
  • 累计撰写 793 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论
标签搜索

目 录CONTENT

文章目录

DataTables

Dettan
2021-04-10 / 0 评论 / 0 点赞 / 185 阅读 / 3,251 字
温馨提示:
本文最后更新于 2022-07-23,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
中文官网 选项 基本curd例子
Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。 分页,即时搜索和排序 几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理 支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation 各式各样的扩展: Editor, TableTools, FixedColumns …… 丰富多样的option和强大的API 支持国际化 超过2900+个单元测试 免费开源 ( MIT license )! 商业支持
表格内嵌操作按钮获取数据
"columns": [
    {
        "title": "操作",
        render: function (data, type, row, full) {
            var func = [
                {
                    "name": "修改",
                    "fn": "edit(\'" + row.id + "\', table.row($(this).parent().parent()).data()  )",
                    "type": "primary"
                },
                {"name": "删除", "fn": "del(\'" + row.id + "\')", "type": "danger"}
            ]

            return generateButtonHtml(func);
        }
    },
    {"title": "ID", "data": "id", "class": "center"},
    {"title": "文件名", "data": "fileName"},
    {"title": "组织名", "data": "fileOrgName"},
    {"title": "path", "data": "filePath"},
    // {"title": "大小", "data": "fileSize", "class": "center"},
    // {"title": "类型", "data": "fileType", "class": "center"},
    // {"title": "url", "data": "fileUrl", "class": "center"},
    {"title": "更新时间", "data": "updateTime", "class": "center"},
    {"title": "创建时间", "data": "createTime", "class": "center"},

],

dTable.on( 'draw', function () {
    $('.paginate_button.previous').html("<<<");
    $('.paginate_button.next').html(">>>");
    var total_records = dTable.rows().count();
    var page_length = dTable.page.info().length;
    var total_pages = Math.ceil(total_records / page_length);
    var current_page = dTable.page.info().page+1;
    $('.paginate_button.previous').after("<strong>Action "+current_page+" of "+(page_length<0?1:total_pages)+"</strong>");
} );
Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。
分页,即时搜索和排序几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation各式各样的扩展: Editor, TableTools, FixedColumns ……丰富多样的option和强大的API支持国际化超过2900+个单元测试免费开源 ( MIT license )! 
商业支持,商用不用交钱,只是交钱了有专人解决问题

$(document).ready(function() {
    $('#myTable').DataTable({
        "language": { //把提示信息中文化
            "lengthMenu": "显示 _MENU_ 条每页",
            "zeroRecords": "没有记录",
            "infoEmpty": "没有记录",
            "infoFiltered": "(filtered from _MAX_ total records)",
            "columns": [ //控制每一列的排序规则
                null,
                { "orderDataType": "dom-text", type: 'string' },
                { "orderDataType": "dom-text-numeric" },
                { "orderDataType": "dom-select" }
            ]
        },
        stateSave: true, //是否保存table状态
        "dom": '<"top"f>rt<"bottom"lp><"clear">',  //各个元素的位置
        "info":false,  //不显示分页详情
        "lengthMenu": [[10,15, 20,25,30,40, 50, -1], [10,15, 20,25,30,40, 50,"All"]]  //每页显示几条的选项
    } );
    var table = $('#myTable').DataTable();

    $('#myTable tbody').on( 'mouseenter', 'td', function () {
            var colIdx = table.cell(this).index().column;

            $( table.cells().nodes() ).removeClass( 'highlight' );
            $( table.column( colIdx ).nodes() ).addClass( 'highlight' );
        } );
} );

/* Create an array with the values of all the input boxes in a column */
$.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).val();
    } );
};

/* Create an array with the values of all the input boxes in a column, parsed as numbers */
$.fn.dataTable.ext.order['dom-text-numeric'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).val() * 1;
    } );
};

/* Create an array with the values of all the select options in a column */
$.fn.dataTable.ext.order['dom-select'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('select', td).val();
    } );
};

/* Create an array with the values of all the checkboxes in a column */
$.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).prop('checked') ? '1' : '0';
    } );
};

$("#modal-names").empty();

window.location.reload();

[
  {
    "url": "https://api.github.com/repos/ssy341/datatables-cn/issues/463",
    "repository_url": "https://api.github.com/repos/ssy341/datatables-cn",
    "labels_url": "https://api.github.com/repos/ssy341/datatables-cn/issues/463/labels{/name}",
    "comments_url": "https://api.github.com/repos/ssy341/datatables-cn/issues/463/comments",
    "events_url": "https://api.github.com/repos/ssy341/datatables-cn/issues/463/events",
    "html_url": "https://github.com/ssy341/datatables-cn/issues/463",
    "id": 431914439,
    "node_id": "MDU6SXNzdWU0MzE5MTQ0Mzk=",
    "number": 463,
    "title": "ajax 接收functino函数这种类型的参数的callback参数有哪些?",
    "user": {
      "login": "yangyaru0108",
      "id": 19700455,
      "node_id": "MDQ6VXNlcjE5NzAwNDU1",
      "avatar_url": "https://avatars3.githubusercontent.com/u/19700455?v=4",
      "gravatar_id": "",
      "url": "https://api.github.com/users/yangyaru0108",
      "html_url": "https://github.com/yangyaru0108",
      "followers_url": "https://api.github.com/users/yangyaru0108/followers",
      "following_url": "https://api.github.com/users/yangyaru0108/following{/other_user}",
      "gists_url": "https://api.github.com/users/yangyaru0108/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/yangyaru0108/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/yangyaru0108/subscriptions",
      "organizations_url": "https://api.github.com/users/yangyaru0108/orgs",
      "repos_url": "https://api.github.com/users/yangyaru0108/repos",
      "events_url": "https://api.github.com/users/yangyaru0108/events{/privacy}",
      "received_events_url": "https://api.github.com/users/yangyaru0108/received_events",
      "type": "User",
      "site_admin": false
    },
    "labels": [

    ],
    "state": "open",
    "locked": false,
    "assignee": null,
    "assignees": [

    ],
    "milestone": null,
    "comments": 0,
    "created_at": "2019-04-11T09:13:36Z",
    "updated_at": "2019-04-11T09:13:36Z",
    "closed_at": null,
    "author_association": "NONE",
    "body": "<!--\r\n以下内容为注释说明\r\n1. 请使用markdown语法进行编辑 \r\n2. 请提供必要信息,以便于更好的获知问题,以提出恰当的解决方案\r\n3. Issue的title请明确说明errorMessage\r\n4. 代码部分务必使用code进行处理\r\n5. 请提供以下信息,包括但不限于:\r\n-->\r\n\r\n#### 1 使用DataTables的ajax自定义数据\r\n\r\n\r\najax: function (data, callback, settings) {\r\n\t$.ajax({\r\n\t\turl: \&quot;/ssc/tamperproof/log/\&quot;,\r\n\t\ttype: \&quot;get\&quot;,\r\n\t\tasync:false,\r\n\t\tcontentType: 'application/json',\r\n\t\tsuccess: function (res) {\r\n\t\t\t//封装返回数据\r\n var returnData;\r\n\t\t\treturnData.data = res_data;\r\n\t\t\tcallback(returnData);\r\n\t\t}\r\n\t});\r\n}\r\n\r\n callback的参数returnData这个对象除了可以传递data还有其他的属性吗?都在那里可以看到?\r\n"
  }
上面是数据下面是代码。



  var githubTable;
    $(document).ready(function () {

        //配置DataTables默认参数
        $.extend(true, $.fn.dataTable.defaults, {
            "language": {
                    "processing": "处理中...",
    "lengthMenu": "显示 _MENU_ 项结果",
    "zeroRecords": "没有匹配结果",
    "info": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
    "infoEmpty": "显示第 0 至 0 项结果,共 0 项",
    "infoFiltered": "(由 _MAX_ 项结果过滤)",
    "infoPostFix": "",
    "search": "搜索:",
    "searchPlaceholder": "搜索...",
    "url": "",
    "emptyTable": "表中数据为空",
    "loadingRecords": "载入中...",
    "infoThousands": ",",
    "paginate": {
        "first": "首页",
        "previous": "上页",
        "next": "下页",
        "last": "末页"
    },
    "aria": {
        "paginate": {
            "first": "首页",
            "previous": "上页",
            "next": "下页",
            "last": "末页"
        },
        "sortAscending": "以升序排列此列",
        "sortDescending": "以降序排列此列"
    },
    "thousands": "."
            },
            "dom": "l<'#toolbar'>frtip"
        });

        //issue表格初始化
        githubTable = $("#issueTable").DataTable({
            //调用github api 获取issues 数据
            ajax: {
                url: "https://api.github.com/repos/ssy341/datatables-cn/issues",
                dataSrc: ""
            },
            //默认最后一列(最后更新时间)降序排列
            order: [[4, "desc"]],
            //行被创建回调
            createdRow: function (row, data, dataIndex) {
                var updated_at = new Date(Date.parse(data.updated_at)).Format("yyyy-MM-dd hh:mm:ss");
                updated_at = new Date(updated_at).getTime();
                var current = new Date().getTime();
                var bl = current - updated_at;
                var s = 5 * 24 * 60 * 60 * 1000;
                //最后更新日期在最近5天则突出显示
                if (bl < s) {
                    $(row).addClass('unread');
                }
            },
            //行创建完成后回调
            rowCallback: function (row, data, index) {
                var tags = $(row).find("td:eq(1)");
                if (tags.text().indexOf("置顶") > 0) {
                    var title = $(row).find("td:eq(0)");
                    var hot = "<span class='hot'></span>";
                    title.html(title.html() + hot);
                }
            },
            columnDefs: [
                {
                    targets: 4,
                    data: "updated_at",
                    title: "<i class='icon-time'></i>",
                    render: function (data, type, row, meta) {
                        return new Date(Date.parse(data)).Format("yyyy-MM-dd hh:mm:ss");
                    }
                },
                {
                    targets: 3,
                    data: null,
                    title: "<i class='icon-user'></i>",
                    render: function (data, type, row, meta) {
                        return "<a href='" + row.user.html_url +
                            "' target='_blank'>" + row.user.login + "</a>";
                    }
                },
                {
                    targets: 2,
                    data: "comments",
                    title: "<i class='icon-comment'></i>",
                    render: function (data, type, row, meta) {
                        var comments = data + "<i class='icon-comment'></i>";
                        return comments;
                    }
                },
                {
                    targets: 1,
                    data: null,
                    title: "<i class='icon-tag'></i>",
                    render: function (data, type, row, meta) {
                        var labels = "";
                        if (row.labels.length) {
                            for (var j = 0, labelslen = row.labels.length; j < labelslen; j++) {
                                labels += "<span style='color:#" + row.labels[j].color + "' >" +
                                    row.labels[j].name + "</span>";
                                if (j != labelslen - 1) {
                                    labels += ",";
                                }
                            }
                        }
                        return labels;
                    }
                },
                {
                    targets: 0,
                    data: "title",
                    title: "<i class='icon-question-sign'></i>",
                    render: function (data, type, row, meta) {
                        var title = "<a href='" + row.html_url +
                            "' target='_blank'>" + row.title + "</a>";
                        return title;
                    }
                }
            ],
            initComplete: function () {
                //表格加载完毕,手动添加按钮到表格上
                $("#toolbar").css("width", "100px").css("display", "inline").css("margin-left", "10px");
                $("#toolbar").append("<a href='https://github.com/ssy341/datatables-cn/issues/new' " +
                    "class='btn btn-primary btn-sm' target='_blank'>我有问题</a>");
                $("#toolbar").append("<a href='/example/diy.html' " +
                    "class='btn btn-default btn-sm' style='margin-left: 5px' target='_blank'>DIY</a>");
                $("#toolbar").append("<a href='javascript:void(0);' " +
                    "class='btn btn-default btn-sm closedIssue' " +
                    "style='margin-left: 5px;color:#009900'>查看已解决问题</a>");
                $("#toolbar").append("<a href='javascript:void(0);' " +
                    "class='btn btn-default btn-sm viewCode' style='margin-left: 5px;'>查看本实例代码</a>");

                //加载已经关闭的问题
                $(".closedIssue").clickToggle(function () {
                    //调用url方法切换dt的数据源
                    githubTable.ajax.url("https://api.github.com/repos/ssy341/datatables-cn/issues?state=closed").load();
                    $(this).text("查看未解决问题").css("color", "#FF0000");
                }, function () {
                    githubTable.ajax.url("https://api.github.com/repos/ssy341/datatables-cn/issues").load();
                    $(this).text("查看已解决问题").css("color", "#009900");
                });

                //查看本例子代码
                $(".viewCode").click(function(){
                    //显示模态框展示代码
                    $("#issueTableCode").modal("show");
                    $("#issueTableCodeContent").html($("#issueTableScript").html());
                });
            }
        });
    });

    //时间格式化
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1,
            //月份
            "d+": this.getDate(),
            //日
            "h+": this.getHours(),
            //小时
            "m+": this.getMinutes(),
            //分
            "s+": this.getSeconds(),
            //秒
            "q+": Math.floor((this.getMonth() + 3) / 3),
            //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    };

    //事件来回切换方法
    //solve this
    //reference http://stackoverflow.com/questions/4911577/jquery-click-toggle-between-two-functions
    (function ($) {
        $.fn.clickToggle = function (func1, func2) {
            var funcs = [func1, func2];
            this.data('toggleclicked', 0);
            this.click(function () {
                var data = $(this).data();
                var tc = data.toggleclicked;
                $.proxy(funcs[tc], this)();
                data.toggleclicked = (tc + 1) % 2;
            });
            return this;
        };
    }(jQuery));

$(document).ready(function() {
    table=$('#myTable').DataTable({
        "language": { //把提示信息中文化
            "processing": "处理中...",
            "lengthMenu": "每页显示 _MENU_ 条数据",
            "zeroRecords": "没有匹配结果",
            "infoFiltered": "(由 _MAX_ 项结果过滤)",
            "infoPostFix": "",
            "search": "搜索:",
            "searchPlaceholder": "搜索...",
            "url": "",
            "emptyTable": "表中数据为空",
            "loadingRecords": "载入中...",
            "infoThousands": ",",
            "paginate": {
                "previous": "上一页",
                "next": "下一页",
            },
            "aria": {
                "paginate": {
                    "previous": "上一页",
                    "next": "下一页",
                },
                "sortAscending": "以升序排列此列",
                "sortDescending": "以降序排列此列"
            },
            "columns": [ //控制每一列的排序规则
                null,
                {"orderDataType": "dom-text", type: 'string'},
                {"orderDataType": "dom-text-numeric"},
                {"orderDataType": "dom-select"}
            ]
        },
        stateSave: true, //是否保存table状态
        "dom": '<"top"f<"toolbar">>rt<"bottom"lp><"clear">',  //各个元素的位置,插入一个class="toolbar"的div然后在下面往里添加元素
        "info": false,  //不显示分页详情
        "lengthMenu": [[10, 15, 20, 25, 30, 40, 50, -1], [10, 15, 20, 25, 30, 40, 50, "All"]],  //每页显示几条的选项
        initComplete: function () {
            //表格加载完毕,手动添加按钮到表格上
            $(".toolbar").css("width", "82px").css("display", "inline").css("float", "right")
            .append("<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#modal-add' data-type='random'>添加学校</button>");
        }
    });

    $('#myTable tbody').on('mouseenter', 'td', function () {
        var colIdx = table.cell(this).index().column;

        $(table.cells().nodes()).removeClass('highlight');
        $(table.column(colIdx).nodes()).addClass('highlight');
    });
});

0

评论区