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

DataTables

Dettan
2021-04-10 / 0 评论 / 0 点赞 / 114 阅读 / 17,166 字
温馨提示:
本文最后更新于 2022-04-30,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
中文官网 选项 基本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, {
        &quot;language&quot;: {
                &quot;processing&quot;: &quot;处理中...&quot;,
&quot;lengthMenu&quot;: &quot;显示 _MENU_ 项结果&quot;,
&quot;zeroRecords&quot;: &quot;没有匹配结果&quot;,
&quot;info&quot;: &quot;显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项&quot;,
&quot;infoEmpty&quot;: &quot;显示第 0 至 0 项结果,共 0 项&quot;,
&quot;infoFiltered&quot;: &quot;(由 _MAX_ 项结果过滤)&quot;,
&quot;infoPostFix&quot;: &quot;&quot;,
&quot;search&quot;: &quot;搜索:&quot;,
&quot;searchPlaceholder&quot;: &quot;搜索...&quot;,
&quot;url&quot;: &quot;&quot;,
&quot;emptyTable&quot;: &quot;表中数据为空&quot;,
&quot;loadingRecords&quot;: &quot;载入中...&quot;,
&quot;infoThousands&quot;: &quot;,&quot;,
&quot;paginate&quot;: {
    &quot;first&quot;: &quot;首页&quot;,
    &quot;previous&quot;: &quot;上页&quot;,
    &quot;next&quot;: &quot;下页&quot;,
    &quot;last&quot;: &quot;末页&quot;
},
&quot;aria&quot;: {
    &quot;paginate&quot;: {
        &quot;first&quot;: &quot;首页&quot;,
        &quot;previous&quot;: &quot;上页&quot;,
        &quot;next&quot;: &quot;下页&quot;,
        &quot;last&quot;: &quot;末页&quot;
    },
    &quot;sortAscending&quot;: &quot;以升序排列此列&quot;,
    &quot;sortDescending&quot;: &quot;以降序排列此列&quot;
},
&quot;thousands&quot;: &quot;.&quot;
        },
        &quot;dom&quot;: &quot;l&lt;'#toolbar'&gt;frtip&quot;
    });

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

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

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

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

评论区