使用jquery.datatable.js注意事項

本文連接:https://blog.csdn.net/ylg01/article/details/76463908
寫在最前面的話,若是不是維護老項目或者在老項目上二次開發儘可能不要用這個表格插件html

爲何呢?jquery

1.老項目基本用的是1.09及以前的版本;這個插件1.09和1.10以後的版本命名及加載方式,徹底改變了;1.09版本的APIajax

基本沒有英文的我是沒找到,中文呢基本靠博客中的隻言片語,但這些博客不少是有錯誤的,包括我本身寫的可能都是有些方法沒理解透形成的問題,json

不過這個插件真的很差用bootstrap

http://datatables.club/upgrade/1.10-convert.html  1.09和1.10的一些對比app

 

2.這個插件的sdom參數有人說強大,可是我以爲這個參數對於UI優化簡直是個大坑dom

 

3.一個寫的比較全的的API博客異步

參數配置:http://blog.csdn.net/zhu_xiao_yuan/article/details/51252300ide

回調函數:http://www.cnblogs.com/zhangwei595806165/p/3701463.html函數

 

列舉遇到的一些問題及解決辦法

1.全部頁面表格的公共初始化方法:1.10有個default方法,1.09以前是木有的;可是又不想重複js代碼維護起來也麻煩,有倆種方式1、   反壓縮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']
}],

};

2、在公共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="#">&larr; ' +
oLang.sPrevious +'</a></li>' +'<li class="next disabled"><a href="#">' +
oLang.sNext +' &rarr; </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("");

相關文章
相關標籤/搜索