使用jquery.datatable.js注意事项
本文链接:https://blog.csdn.net/ylg01/article/details/76463908
写在最前面的话,如果不是维护老项目或者在老项目上二次开发尽量不要用这个表格插件
为什么呢?
1.老项目基本用的是1.09及之前的版本;这个插件1.09和1.10之后的版本命名及加载方式,完全改变了;1.09版本的API
基本没有英文的我是没找到,中文呢基本靠博客中的只言片语,但这些博客很多是有错误的,包括我自己写的可能都是有些方法没理解透造成的问题,
不过这个插件真的不好用
http://datatables.club/upgrade/1.10-convert.html 1.09和1.10的一些对比
2.这个插件的sdom参数有人说强大,但是我觉得这个参数对于UI优化简直是个大坑
3.一个写的比较全的的API博客
参数配置:http://blog.csdn.net/zhu_xiao_yuan/article/details/51252300
回调函数:http://www.cnblogs.com/zhangwei595806165/p/3701463.html
列举遇到的一些问题及解决办法
1.所有页面表格的公共初始化方法:1.10有个default方法,1.09之前是木有的;但是又不想重复js代码维护起来也麻烦,有俩种方式一、 反压缩jQuery.datatable.js在2050行左右修改代码如下:浅红色的是我修改的一些公共初始化
j.defaults = {
sPaginationType: "bootstrap",
bLengthChange: true,
bPaginate: true,
iDisplayStart: 0,
iDisplayLength: 10,
aLengthMenu: [10, 20, 50],
bAutoWidth: false,
bFilter: false,
bDestroy:true,
bProcessing: true,
bRetrieve: true,
bServerSide: true,
bSort: false,
iCookieDuration: 60 * 60 * 24 * 7,
oLanguage: {
sInfo: "当前第 _START_ - _END_ 条 共计 _TOTAL_ 条",
sInfoEmpty: "当前第 0 - 0条 共计 0 条",
sInfoFiltered: "(从 _MAX_ 条记录中过滤)",
sLengthMenu: "每页显示 _MENU_条",
sLoadingRecords: "加载中...",
sProcessing: "加载中...",
sSearch: "搜索:",
sZeroRecords: "没有找到符合条件的数据",
sEmptyTable: "没有找到符合条件的数据",
oPaginate: {
sFirst: "首页",
sLast: "尾页",
sNext: "下一页",
sPrevious: "上一页"
},
oAria: {
sSortAscending: ": activate to sort column ascending",
sSortDescending: ": activate to sort column descending"
},
sInfoPostFix: "",
sInfoThousands: ",",
sUrl: "",
},
aoColumnDefs: [{
sDefaultContent: '',
aTargets: ['_all']
}],
};
二、在公共js中对表格都加载一次
这种方式有点不好就是当我不需要展现表格的时候它也请求了一次后台;span12-pag{width:96%}是自己写的一个样式,插件的分页条长度超过了表格宽度
$(".datatable").datatable({
"sScrollY": 474, // DataTables的高
"sDom": "<'box-content'<'span12'l>tr<'span12 span12-pag'p>>",
})
2.1.09版本没有提供一个异步加载的方法,以下自己封装的一个
// 异步刷新表格数据
$.fn.dataTableExt.oApi.fnReloadAjax = function(oSettings) {
this.fnClearTable(false);
this.oApi._fnProcessingDisplay(oSettings, true);
var that = this;
$.getJSON(oSettings.sAjaxSource, null, function(json) {
if(json.aaData!=null) {
for(var i = 0; i < json.aaData.length; i++) {
that.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
that.oApi._fnProcessingDisplay(oSettings, false);
}
});
}
3.自己封装的分页方法,插件提供的俩中默认方式不符合要求
// 分页方法 bootstrap 形式
$.extend($.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function(oSettings, nPaging, fnDraw) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function(e) {
e.preventDefault();
if(oSettings.oApi._fnPageChange(oSettings,e.data.action)) {
fnDraw(oSettings);
}
};
$(nPaging).addClass('pagination')
.append('<ul>' +'<li class="prev disabled"><a href="#">← ' +
oLang.sPrevious +'</a></li>' +'<li class="next disabled"><a href="#">' +
oLang.sNext +' → </a></li>' +'</ul>');
var els = $('a', nPaging);
$(els[0]).bind('click.DT', {
action: "previous"
}, fnClickHandler);
$(els[1]).bind('click.DT', {
action: "next"
}, fnClickHandler);
},
"fnUpdate": function(oSettings, fnDraw) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, j, sClass, iStart, iEnd, iHalf = Math
.floor(iListLength / 2);
if(oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
} else if(oPaging.iPage <= iHalf) {
iStart = 1;
iEnd = iListLength;
} else if(oPaging.iPage >= (oPaging.iTotalPages - iHalf)) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for(i = 0, iLen = an.length; i < iLen; i++) {
// remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// add the new list items and their event
// handlers
for(j = iStart; j <= iEnd; j++) {
sClass = (j == oPaging.iPage + 1) ? 'class="active"' :'';
$('<li ' + sClass + '><a href="#">' +j + '</a></li>')
.insertBefore($('li:last', an[i])[0])
.bind('click',function(e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10) - 1) *oPaging.iLength;
// 这里将分页参数传递至表格初始化中重绘表格,重新load数据
fnDraw(oSettings);
});
}
// add / remove disabled classes from the static
// elements
if(oPaging.iPage === 0) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i])
.removeClass('disabled');
}
if(oPaging.iPage === oPaging.iTotalPages - 1 ||
oPaging.iTotalPages === 0) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
4.当有tab标签页的页面并且有多个表格时,切换tab标签数据展示不是默认第一页:
我是reload表格后,用jquery模拟了一个a标签点击事件,选择器对不同表格可能要略做修改
$(".dataTables_paginate").find("ul").eq(1).children("li").children("a").eq(1).click();
5.bvisible参数,使用该参数需要在需隐藏的列上加上"bvisible":false,通过fnSetColumnVis来控制列的显隐,但是我发现每次调用都请求了一次后台;
有种取巧方式:是将后台数据封装成一个统一的对象名返回,通过选择器修改表头的列名
6.后台返回分页数据
function initTable(urlRwrite) {
objTable = $("#resourceTable").dataTable({
"sScrollY": 530, // DataTables的高
'bFilter': true, // 是否使用内置的过滤功能
"sDom": "<'box-content'<'span6'f><'span6'l>tr<'span12 span12-pag'p>>",
"oLanguage": { // 汉化
"sSearch": "资源名称/URL:",
},
"sAjaxSource":urlRwrite==undefined? "/shore/admin/role/listResource.ajax?projectId=0&T="
+ new Date().getTime():urlRwrite,
"aoColumns": [{
"fnCreatedCell": function(nTd, sData, oData, iRow, iCol) {
var resourceId = oData.fResourceId;
var str = "<input type='checkbox' name='resourceId' id='resourceId-" + resourceId
+ "' οnclick='changeId(this," + resourceId + ")'/>";
$(nTd).html(str);
},
"sWidth": "6%"
}, {
"mDataProp": "fResourceName",
"sWidth": "14%"
}, {
"mDataProp": "fResourceUrl",
"sWidth": "24%"
}, {
"mDataProp": "fLastUpdatedBy",
"sWidth": "18%"
}, {
"mDataProp": "fLastUpdatedTime",
"sWidth": "15%"
}, {
"fnCreatedCell": function(nTd, sData, oData, iRow, iCol) {
var resourceId = oData.fResourceId;
var str = "";
if(projectType == 1) {
str += "<button class='btn btn-success button-margin-right editBtn' type='button'
οnclick='editProperty(" + resourceId + ")' disabled='true'
title='资源必须和角色绑定后才能进行此操作' id='btn1-" + resourceId + "'>
<i class='icon-edit icon-white'></i>编辑属性</button>";
str += "<button class='btn btn-success button-margin-right delBtn btn-top' type='button'
οnclick='editResourceRoleOu(" + resourceId + ")' disabled='true'
title='资源必须和角色绑定后才能进行此操作' id='btn2-" + resourceId + "'>
<i class='icon-edit icon-white'></i>编辑访问权限</button>";
}else{
str += "<button class='btn btn-success button-margin-right btnBtn' type='button'
οnclick='loadBtnAuth(" + resourceId + ")' id='btn3-" + resourceId + "' disabled='true'>
<i class='icon-edit icon-white'></i>按钮授权</button>";
}
$(nTd).html(str);
},
}],
"fnServerData": function(sSource, aoData, fnCallback) {
var iDisplayStart = 0;
var iDisplayLength = 10;
var sSearch = '';
$.each(aoData, function(i, o) {
if(o.name == "iDisplayStart") {
iDisplayStart = o.value;
}
if(o.name == "iDisplayLength") {
iDisplayLength = o.value;
}
if(o.name == "sSearch") {
sSearch = o.value;
}
});
$.ajax({
"type": 'get',
"url": sSource,
"dataType": "json",
"data": {
iDisplayStart: iDisplayStart,
iDisplayLength: iDisplayLength,
sSearch: sSearch
},
"success": function(resp) {
fnCallback(resp);
},
"complete": function(XMLHttpRequest,
textStatus) {
var data = XMLHttpRequest.responseText;
if(data == "timeout") {
window.location = "/";
}
}
});
},
"fnDrawCallback": function() { // 复选框反选操作
$.each(checkedResourceIds, function(i, o) {
if(deleteResourceIds.indexOf(o) == -1) {
$("#resourceId-" + o).prop("checked", true);
$("#btn1-" + o).attr("disabled", false);
$("#btn2-" + o).attr("disabled", false);
$("#btn3-" + o).attr("disabled", false);
$("#btn1-" + o).attr("title", "");
$("#btn2-" + o).attr("title", "");
} else {
$("#resourceId-" + o).prop("checked", false);
}
});
$.each(addResourceIds, function(i, o) {
$("#resourceId-" + o).prop("checked", true);
$("#btn1-" + o).attr("disabled", false);
$("#btn2-" + o).attr("disabled", false);
$("#btn3-" + o).attr("disabled", false);
$("#btn1-" + o).attr("title", "");
$("#btn2-" + o).attr("title", "");
});
},
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
$('td:eq(1)', nRow).html(escapeHtml(aData.fResourceName));
$('td:eq(2)', nRow).html(escapeHtml(aData.fResourceUrl));
$('td:eq(4)', nRow).html(aData.fLastUpdatedTime.substring(0,aData.fLastUpdatedTime.length-2));
}
})
}
7.定义列框时只在表头定义width是无效的,必须在列中定义:"sWidth": "14%"
8.对表格数据的字符转码和数据格式化可以在fnRowCallback中进行操作
9.对表格定义的复选框翻页无法选中问题可在fnDrawCallback对表格进行操作
10.当表格的异步参数改变时必须修改url否则无法将新的参数传递至后台
11.不知道为啥使用fnClearTable(false)方法并没有清楚数据,我使用了中取巧方式$("tbody").empty("");
使用jquery.datatable.js注意事项的更多相关文章
- jquery.datatable.js与CI整合 异步加载(大数据量处理)
http://blog.csdn.net/kingsix7/article/details/38928685 1.CI 控制器添加方法 $this->show_fields_array=arra ...
- jquery.dataTable.js 基础配置
$(document).ready(function () { $('#dataTables-example').DataTable({ responsive: true, "bPagina ...
- jquery.datatable.js实际运用
$.dataTablesSettings = { deferRender: true,// 当处理大数据时,延迟渲染数据,有效提高Datatables处理能力 bStateSave: true,//表 ...
- jquery.Datatable.js
http://www.cnblogs.com/nier/archive/2012/03/18/2404836.html http://blog.csdn.net/mickey_miki/article ...
- jquery dataTable汉化(插件形式)
1.jquery dataTable.js 官网:http://datatables.net/ 中文:http://dt.thxopen.com/ 2.汉化提示信息(放到xx.js中,引入即可) 注: ...
- jQuery图片懒加载插件jquery.lazyload.js使用实例注意事项说明
jQuery图片懒加载插件jquery.lazyload.js使用实例注意事项说明 jquery.lazyload.js是一个用JavaScript编写的jQuery插件.它可以延迟加载长页面中的图片 ...
- jquery.datatable插件从数据库读取数据
一.分页 分页的基本思想是根据datatable的页码及每页显示的行数,将数据从数据库分段提出,然后再填充到表格中,以达到分页的效果. 这里需要用到datatable插件的几个属性: "sE ...
- jquery和js cookie的使用解析
JavaScript是运行在客户端的脚本,因此一般是不能够设置Session的,因为Session是运行在服务器端的.而cookie是运行在客户端的,所以可以用JS来设置cookie. 在这里分别通过 ...
- jquery.tablesorter.js 学习笔记
jquery.tablesorter.js 一般情况下,表格数据的排序方式有两种,第一种是让后端服务将排序后的数据直接输出,另外一种方式就是使用客户端排序,而jquery.tablesorter.js ...
随机推荐
- aliyun手记
阿里云里面购买的带宽是指外网带宽,内网默认是千兆带宽,做过I/O优化的则是万兆带宽. 修改密码实在更多(三个点)的那里进行修改的:修改密码(windows是administrator以及Linux是r ...
- Python的网页解析库-PyQuery
PyQuery库也是一个非常强大又灵活的网页解析库,如果你有前端开发经验的,都应该接触过jQuery,那么PyQuery就是你非常绝佳的选择,PyQuery 是 Python 仿照 jQuery 的严 ...
- DApp是什么,DApp是必然趋势
DApp是什么,DApp是必然趋势 https://www.jianshu.com/p/dfe3098de0de Thehrdertheluck关注 12018.04.23 11:54:00字数 2 ...
- POJ-动态规划-背包问题模板
背包问题模板 一.0-1背包 状态:背包容量为j时,求前i个物品所能达到最大价值,设为dp[i][j].初始时,dp[0][j](0<=j<=V)为0,没有物品也就没有价值. 状态转移方程 ...
- LeetCode 1046. 最后一块石头的重量(1046. Last Stone Weight) 50
1046. 最后一块石头的重量 1046. Last Stone Weight 题目描述 每日一算法2019/6/22Day 50LeetCode1046. Last Stone Weight Jav ...
- 【手写代码】快速计算数字x有多少个二进制1
#include<bits/stdc++.h> #include<vector> using namespace std; int f1(int x) { ; ) { )==) ...
- 卓金武《MATLAB在数学建模中的应用》 第2版
内容介绍 本书的作者都具有实际的数学建模参赛经历和竞赛指导经验.书中内容完全是根据数学建模竞赛的需要而编排的,涵盖了绝大部分数学建模问题的matlab求解方法.本书内容分上下两篇.上篇介绍数学建模中常 ...
- 【转帖】Intel AMD 龙芯2019年12月份最新产品线
Intel未来三代U集体曝光:14nm退回去了! https://news.cnblogs.com/n/651244/ 不过没搞懂 为啥中芯国际已经开始量产14nm了 龙芯为什么不用.. 3A4000 ...
- 向DataGrid数据表格增加查询搜索框
向DataGrid数据表格增加查询搜索框 效果如下: js代码: $(function(){ var dg = $('#dg').datagrid({ url:"${pageContext. ...
- PHP下载远程图片到本地的几种方法总结(tp5.1)
1.CURL 2.使用file_get_contents 3.使用fopen 参考链接:https://www.jb51.net/article/110615.htm