
// @author 文志新 http://jsfiddle.net/wenyi/47nz7ez9/3/ /**關於插件的通用構造 * * 構造函數PluginName($trigger,options)傳入觸發元素和配置項,以便在構造函數中使用觸發元素 * 寫在$.fn.pluginName外圍,通過實例化$ele.data('bootstrap.table',(dat=new BootstrapTable(this,options))); * 實例寫在觸發元素的data屬性中,以便調用該實例,避免多次創造實例; * $.fn.pluginName(option)參數是對象,執行構造函數PluginName,產生新的實例; * 是字符串,調用data對象中存儲的實例執行方法,提供PluginName.prototype的方法接口; * 脫離在構造函數PluginName及其原型中的函數,通過$.fn.pluginName.util暴露接口; * 構造函數PluginName使用$ele.trigger提供事件接口; * 配置項可以是html頁面data數據配置、或者$.fn.pluginName參數option配置; * 在html中的配置可以方便使用模板引擎傳值實現初始化,后台java使用content.put方法; * 默認配置項利用js中一切都是對象的特點附着在PluginName.DEFAULTS; * * 構造函數渲染頁面時,先填充頁面內容,再綁定事件; * 綁定事件通過$ele.off(eventType).on(eventType,function(){})先解綁; * * 書寫有分支具體情況到主干通用情況,類似先做能力檢測,再做瀏覽器嗅探 * 應用場景,if(){return};抽離分支具體情況,后續代碼對主干通用情況進行處理 * 優先檢測具體的配置項,其次對自定義配置項、默認配置項作混合處理 * 預先配置子條目的顯示情況、數據信息,再次配置父條目的顯示情況、配置信息 * * if語句傳遞設置的詳情變量時,先順序設置頭部,再針對一般情況進行處理,其次設置尾部 * 類似插件作者對分頁切換頁面按鈕的處理, * 借form、to設置起始頁展示情況,再是兩串...,最后是尾頁的顯示情況 */ /**關於jquery * * data: * $(ele).data()以對象形式返回; * $(ele).data({url:"www.baidu.com"})以對象形式設置data屬性; * $(ele).data(url,{param:"www.baidu.com"})以對象形式設置某個data屬性; * * event: * $.proxy(fn,content)調用的函數fn,傳入的上下文content; * $.Event(eventType,arguments)轉化成事件,並傳入參數,只可使用一次; * * type: * $.isNumeric()判斷變量是否數值型或數字值字符串,包含十六進制等; * $.isFunction()判斷是否為函數; * $.isEmptyObject()是否為空對象; * $.isPlainObject()是否為對象字面量; * $.isArray()是否數組; * $.type()判斷類型; * * util: * $.grep([]/{},function(item,index))過濾出返回值為真的數組; * $.map([]/{},function(item,index))過濾出以返回值為數組元素的數組; * $.inArray()返回元素在數組中的位置; */ /**bootstap * 使用caret樣式實現三角形; */ /**技巧 * * 使用數組拼接字符串,這樣做方便使用三目運算符處理可變的內容; * * i<0?[]:{} 三目運算符后跟數組或對象; * * 三目運算符以[]包裹,獲取對象的屬性; * * "paramName".split(/(?=[A-Z])/) 返回結果為["param","Name"]; * * str.replace(/%s/g, function(){}) 對每個匹配值應用函數; * * [{i:1},{j:2}].sort(function(a,b){}) a、b為數組元素; * * 非字符串數組對象使用toString()方法轉換后,再調用localeCompare進行比較; * * ~~利用按位非轉化成整數型; * * Object.getOwnPropertyNames以數組形式返回對象的屬性; * * scrollWidth包含超過可視區域的長度; * clientWidth可視區域不包括滾動條的寬度; * offsetWidth可視區域包括滾動條的寬度; * outerWidth包括內邊距、邊框的寬度; * outerWidth(true)包括內邊距、邊框、外邊距的寬度; * innerWidth包括內邊距、不包括邊框的寬度; * * scrollLeft()獲取元素的水平偏移,有水平滾動條的情況下; * scrollTop()獲取元素的垂直偏移,有垂直滾動條的情況下; * * 通過hide()方法隱藏的元素可以用:hidden偽類獲取; */ /**關於本插件 * * html頁面配置項寫在觸發元素的data屬性,在$.prototype.bootstrapTable方法將其和默認配置項合並; * 觸發元素還包含表格內容如表頭信息,在構造函數Bootstrap中獲取該信息,與配置項對應內容合並; * js配置的優先級高於html頁面配置項,initTable獲取頁面配置thead>tr>th、tbody>tr>td信息; * 表體渲染通過this.data實現,搜索、排序以及其他方法更新this.data數據,實現數據和顯示分離; */ !function ($) { 'use strict'; /**工具函數 * * sprintf(str,str1,str2): * sprintf("<span style='%s'>%s</span>","text-align:center"."hello"); * 順序替換文本,無替換文本返回空; * * getPropertyFromOther(list,from,to,value): * getPropertyFromOther(this.columns,'field','title',value); * 獲取field屬性為value的數組元素的title屬性值this.columns[i].title; * 應用場景:卡片式顯示時需要獲取標題欄的顯示文案信息; * * getFieldIndex(columns,field): * getFieldIndex(this.columns,field); * 獲取field屬性為field的數組元素的列坐標this.columns[i].filedIndex; * * setFieldIndex(this.options.columns): * setFieldIndex([[ {colspan:4,title:'Group1'},// 跨幾列 {rowspan:3,title:'ID'},// 跨幾行 ],[ {rowspan:2,title:'Name1'}, {colspan:3,title:'Group2'}, ],[ {title:'Name2'}, {title:'Name3'}, {title:'Name4'}, ]]) * 為每條標題欄數據設置filedIndex:所在列/列坐標; * 無field主鍵的標題欄數據以列坐標作為field屬性的值; * 意義:借用this.columns[fieldIndex]=column構建this.columns; * this.column的數據格式為{[column]},列坐標相同的標題欄取靠后的子標題; * 問題:用戶配置options.columns時需要順序寫就標題欄,以子標題不跨列為前提,函數的應用場景變得有限; * * getScrollBarWidth獲取滾動條的寬度; * * calculateObjectValue(self,name,args,defaultValue): * 當name為字符串時,獲取window對象的方法並執行,參數為args,沒有該方法時調用sprintf替換name文本; * 當name為函數時,傳入args執行該函數; * 以上情況都不是返回defaultValue; * 問題:原型中的方法可以直接調用,window對象的方法使用戶配置變得繁瑣,sprintfy也可以預先作判斷后調用; * * compareObjects(objectA,objectB,compareLength): * compareObjects(this.options, options, true); * 當compareLength為真時,先比較兩個對象的長度是否相同,其次比較同名元素是否等值; * 當compareLength為否時,只比較兩個對象的同名元素是否等值; * 問題:在插件中的使用,依賴this.options和options長度相等,且沒有不同名的屬性; * * escapeHTML轉義; * * getRealHeight($el): * 以子元素的最大高度作為父元素的高度; * * getRealDataAttr($(this).data()): * 將paramName的data屬性轉換成param-name修改完成后輸出; * * getItemField(item,field,escape): * 當field為函數時,獲取item[field]並進行轉義(escape為真的情況下); * 當field為字符串時,以最末一個點號后的字符獲取item中的屬性並進行轉義(escape為真的情況下); * 問題:實際應用場景field多是字符串,且沒有點號,可以限制用戶配置使調用函數變得方便; * * isIEBrowser是否IE瀏覽器或者Trident呈現引擎; */ var cachedWidth = null; // 順序替換文本,無替換文本返回空; var sprintf = function (str) { var args = arguments, flag = true, i = 1; str = str.replace(/%s/g, function () { var arg = args[i++];// 對每個匹配值應用函數,i自加1,直到無匹配值; if (typeof arg === 'undefined') { flag = false; return ''; } return arg; }); return flag ? str : ''; }; // 獲取from屬性為value的數組元素的to屬性值this.columns[i].to; // 應用場景,卡片式顯示時需要獲取標題欄的顯示文案信息; var getPropertyFromOther = function (list, from, to, value) { var result = ''; $.each(list, function (i, item) { if (item[from] === value) { result = item[to]; return false; } return true; }); return result; }; // 獲取field屬性為field的數組元素的列坐標this.columns[i].filedIndex; var getFieldIndex = function (columns, field) { var index = -1; $.each(columns, function (i, column) { if (column.field === field) { index = i; return false; } return true; }); return index; }; // 為每條標題欄數據設置filedIndex:所在列/列坐標; /** * 策略: * 表頭分割成columns.length(總行數)* totalCol(總列數)的矩陣,以flag矩陣標記為false; * 各標題欄為columns[i][j].rowspan(行數)* columns[i][j].colspan(列數)的小矩陣; * 從左自右、從上而下遍歷標題欄小矩陣,將標題欄對應的flag首行、首列標記為true; * 因標題欄只能跨列或跨行,不能既跨行又跨列,函數的實現依賴用戶輸入正確的options.columns格式, */ var setFieldIndex = function (columns) { var i, j, k, totalCol = 0, flag = []; for (i = 0; i < columns[0].length; i++) { totalCol += columns[0][i].colspan || 1;// 表格總列數; } for (i = 0; i < columns.length; i++) {// columns.length表格總行數; flag[i] = []; for (j = 0; j < totalCol; j++) { flag[i][j] = false; } } for (i = 0; i < columns.length; i++) { for (j = 0; j < columns[i].length; j++) {// columns[i].length某行共有多少元素; var r = columns[i][j], rowspan = r.rowspan || 1, colspan = r.colspan || 1, // i為標題欄小矩陣在flag大矩陣的行位置; // index記錄標題欄小矩陣在flag大矩陣的列位置; index = $.inArray(false, flag[i]); if (colspan === 1) { // fieldIndex記錄每個標題欄的列坐標信息; r.fieldIndex = index; if (typeof r.field === 'undefined') { r.field = index; } } // 目的是讓$.inArray(false, flag[i])正確獲取標題欄的列坐標; for (k = 0; k < rowspan; k++) { flag[i + k][index] = true; } for (k = 0; k < colspan; k++) { flag[i][index + k] = true; } } } }; // 獲取滾動條的寬度; var getScrollBarWidth = function () { if (cachedWidth === null) { var inner = $('<p/>').addClass('fixed-table-scroll-inner'), outer = $('<div/>').addClass('fixed-table-scroll-outer'), w1, w2; outer.append(inner); $('body').append(outer); w1 = inner[0].offsetWidth; outer.css('overflow', 'scroll'); w2 = inner[0].offsetWidth; if (w1 === w2) { w2 = outer[0].clientWidth; } outer.remove(); cachedWidth = w1 - w2; } return cachedWidth; }; // 當name為字符串時,獲取window對象的方法並執行,參數為args,沒有該方法時調用sprintf替換name文本; // 當name為函數時,傳入args執行該函數;以上情況都不是返回defaultValue; var calculateObjectValue = function (self, name, args, defaultValue) { var func = name; if (typeof name === 'string') { // support obj.func1.func2 var names = name.split('.'); if (names.length > 1) { func = window; $.each(names, function (i, f) { func = func[f]; }); } else { func = window[name]; } } if (typeof func === 'object') { return func; } if (typeof func === 'function') { return func.apply(self, args); } if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) { return sprintf.apply(this, [name].concat(args)); } return defaultValue; }; // 當compareLength為真時,先比較兩個對象的長度是否相同,其次比較同名元素是否等值; // 當compareLength為否時,只比較兩個對象的同名元素是否等值; var compareObjects = function (objectA, objectB, compareLength) { var objectAProperties = Object.getOwnPropertyNames(objectA), objectBProperties = Object.getOwnPropertyNames(objectB), propName = ''; if (compareLength) { if (objectAProperties.length !== objectBProperties.length) { return false; } } for (var i = 0; i < objectAProperties.length; i++) { propName = objectAProperties[i]; if ($.inArray(propName, objectBProperties) > -1) { if (objectA[propName] !== objectB[propName]) { return false; } } } return true; }; // 轉義; var escapeHTML = function (text) { if (typeof text === 'string') { return text .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/`/g, '`'); } return text; }; // 以子元素的最大高度作為父元素的高度; var getRealHeight = function ($el) { var height = 0; $el.children().each(function () { if (height < $(this).outerHeight(true)) { height = $(this).outerHeight(true); } }); return height; }; // 將paramName的data屬性轉換成param-name修改完成后輸出; var getRealDataAttr = function (dataAttr) { for (var attr in dataAttr) { // "paramName".split(/(?=[A-Z])/) 返回結果為["param","Name"]; var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase(); if (auxAttr !== attr) { dataAttr[auxAttr] = dataAttr[attr]; delete dataAttr[attr]; } } return dataAttr; }; // 當field為函數時,獲取item[field]並進行轉義(escape為真的情況下); // 當field為字符串時,以最末一個點號后的字符獲取item中的屬性並進行轉義(escape為真的情況下); var getItemField = function (item, field, escape) { var value = item; if (typeof field !== 'string' || item.hasOwnProperty(field)) { return escape ? escapeHTML(item[field]) : item[field]; } var props = field.split('.'); for (var p in props) { value = value && value[props[p]]; } return escape ? escapeHTML(value) : value; }; // 瀏覽器嗅探,匹配IE瀏覽器或呈現引擎Trident的返回為真; var isIEBrowser = function () { return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)); }; /**BootstrapTable構造函數 * * this.$el帶table標簽的觸發元素,置入this.$tableBody中; * this.$container最外層包裹元素.bootstrap-table; * this.$toolbar即是.bootstrap-table下工具欄元素.fixed-table-toolbar; * this.$pagination即是.bootstrap-table下分頁元素.fixed-table-pagination; * this.$tableContainer即是.bootstrap-table下標題內容元素.fixed-table-container; * this.$tableHeader即是.fixed-table-container下表頭元素.fixed-table-header; * this.$tableBody即是.fixed-table-container下表體元素.fixed-table-body; * this.$tableFooter即是.fixed-table-container下表尾元素.fixed-table-footer; * this.$tableLoading即是.fixed-table-container下加載中提示元素.fixed-table-loading; * this.$header即是this.$el下的thead元素; * this.$header_即是對this.$header的克隆,置入this.$tableHeader中,目的是實現表體的滾動; * this.options.toolbar用戶自定義按鈕組,置入this.$toolbar中; * * * * this.options.column: * 混合js和html表頭標題欄的配置項,包括thead>tr的class/title/html/rowspan/colspan/data; * this.columns: * 以this.columns[fieldIndex]的數組形式[columns]記錄表體相應標題欄的數據內容; * this.options.data: * 有js配置,獲取js配置,沒有js配置,獲取html配置; * 包含tbody>tr的id/class/data,tbody>tr>td的html/id/class/rowspan/title/data; * this.header.fields: * 以this.header.fields[column.fieldIndex]數組形式[field]記錄表體每列數據的主鍵; * 應用場景:渲染表體td時由該主鍵通過getFieldIndex獲取this.columns的序號; * 問題:不能直接通過tr的序號獲取this.columns數據,或者VisibleColumns數據??? * this.header.fields剔除了this.columns中visible為false的內容; * this.header.styles、this.header.classes: * 數組形式存儲經過處理的每列數據的樣式、類; * this.header.formatters、this.header.cellStyles、this.header.sorters: * 數組形式存儲格式化函數、設置單元格樣式函數、排序函數,或者window方法名; * this.header.events、this.header.sortNames、this.header.searchables: * 數組形式存儲表體相應標題欄配置的事件events、上傳排序的字段sortName、可搜索searchable; * 應用場景:由主鍵名在this.header.fields的位置鎖定對應的事件、排序字段、可搜索; * this.header.stateField: * 復選框內容上傳時的字段名; * this.data: * initSearch搜索前以及執行filterBy方法前與this.options.data等值; * 搜索后this.data為過濾后數據; * data的數據格式: 對象形式 [{ // 行tr中的屬性設置 _data:{ index:1,// 后續會自動賦值為數據在當前頁的所在行號 field:field }, _id:id, _class:class, field1:value1,field2:value2, //填充在單元格中的顯示內容,從this.header.fields數組中獲取屬性名field1等 _field_id }] // 每一行特定的樣式、屬性根據this.options.rowStyle、this.options.rowAttributes獲取 數組形式 [["field","class"]] // 數組形式不能對每一行添加特定的data屬性、id以及class // 特定的的樣式、屬性仍可由this.options.rowStyle、this.options.rowAttributes獲取 // 以及data-index添加行號、data-uniqueId每行的唯一標識,根據options.uniqueId從data中獲取 * this.options.data: * initSearch搜索前以及執行filterBy方法前與this.data等值; * 搜索后this.data為未過濾數據; * 應用場景:搜索未使用前后台數據交互,通過this.options.data獲取新的過濾數據this.data; * this.searchText: * this.text: * 搜索文本; * this.filterColumns: * options.data和this.filterColumns相符則在this.data中保留,不相符則在this.data中刪除; * prototype.filterBy方法使用; * * * * init(): * 初始化函數; * initLocale(): * 將語言包添加進配置項this.options中,數據格式是{formatLoadingMessage:fn}; * initContainer(): * 創建包裹元素this.container及其子元素this.$toolbar、this.$pagination等,為表格添加樣式; * initTable(): * 獲取頁面thead>th、tbody>tr>td的配置內容更新options.columns、options.data配置信息; * this.columns記錄表體每列數據相應標題欄options.column的數據內容; * initHeader(): * 由options.columns渲染表頭,th的data-field記為column[field],data數據記為column; * 更新this.header記錄主鍵、樣式、事件、格式化函數等,以及stateField復選框上傳字段; * 綁定事件,包括點擊排序、確認鍵排序、全選,更新上傳數據、頁面狀態等; * initFooter(): * 顯示隱藏表尾; * initData(data,type): * 頁面初始化時this.data賦值為this.options.data; * ajax交互時this.data賦值為后台返回的數據,options.data也同樣更新為后台返回的數據; * type為append時,表格尾部插入數據,this.data、options.data尾部插入相應數據; * type為prepend時,表格頂部插入數據,this.data、options.data頭部插入相應數據; * 前台分頁的情況下調用this.initSort進行排序,后台分頁以返回數據為准; * initSort(): * onSort方法設置點擊排序按鈕時,更新options.sortName為相應標題欄column.field值; * initSort由column.field值獲得相應的sortName; * 調用option.sorter函數或window[option.sorter]方法進行比較排序; * 排序通過更新this.data數據實現,this.data渲染到頁面使用initBody方法; * onSort(): * 點擊排序時更新options.sortName為被排序列數據對應column[field]值,以便initSort獲取sortName; * 更新options.sortOrder為被排序列數據對應column[order]值,或保持原有值; * 觸發sort事件,調用initServer獲取后台數據,調用initSort排序、initBody渲染表體; * initToolbar(): * 創建工具欄內的用戶自定義按鈕組、分頁顯示隱藏切換按鈕、刷新按鈕、篩選條目按鈕; * 以及卡片表格顯示切換按鈕、搜索框,並綁定相應事件;篩選條目時觸發column-switch事件; * onSearch(): * this.text,this.options.text設為搜索框去除兩端空白的值,pageNumber設為1; * 調用initSearch將篩選本地數據;調用updatePagination完成遠程交互或單渲染本地數據; * 觸發search事件; * initSearch(): * 前台分頁的情況下,先通過this.filterColumns通過this.option.data過濾this.data數據; * 再通過搜索文本過濾this.data數據; * 輸入文本和經this.header.formatters或window[this.header.formatters]函數格式化匹配比對; * initPagination(): * 初始化設置分頁相關頁面信息顯示情況,包括當前頁顯示第幾條到第幾天數據,共幾條數據,每頁顯示幾條數據; * 以及每頁顯示數據量切換按鈕,選擇頁面的分頁欄顯示情況,再綁定事件; * 通過options.pageNumber獲取this.pageFrom、this.pageTo,以便前台分頁時initBody獲取相應數據; * updatePagination(): * 分頁點選按鈕有disabled屬性則返回,無則重新布局分頁顯示面板; * maintainSelected為否時,調用resetRows重置復選框為不選中,調用initServer交互或initbody渲染頁面; * initSever由后台返回數據; * initPagination通過options.pageNumber取得options.pageFrom、options.pageTo; * initBody由options.pageFrom、options.pageTo獲取需要渲染的數據data; * 觸發page-change事件; * onPageListChange(): * 每頁顯示數據量下拉列表選中時觸發,替換每頁顯示數據量按鈕文本; * 更新options.pageSize,通過updatePagination調用initPagination設置this.pageFrom、this.pageTo; * updatePagination再調用initServer完成交互,或initBody渲染本地數據; * onPageFirst(): * onPagePre(): * onPageNext(): * onPageLast(): * onPageNumber(): * 更新options.pageNumber,通過updatePagination調用initPagination設置this.pageFrom、this.pageTo; * updatePagination再調用initServer完成交互,或initBody渲染本地數據; * 跳轉分頁首頁、上一頁、下一頁、尾頁,由頁碼跳轉; * initBody(): * fixedScroll為否的情況下,表體移動到頂部; * 通過this.pageFrom、this.pageTo截取this.getData()數據row渲染表體,主要是tbody>tr以及tbody>tr>td; * tbody>tr的data-index設為行號,class、id為row._class、row._id,樣式、data數據通過調用函數獲得; * tbody>tr>td區分為卡片顯示和表格顯示兩類,顯示值取經this.header.formatters[i]處理后的row[field]; * tbody>tr>td其他class、id、title、data取row[_field_class]等; * 綁定展開卡片詳情按鈕點擊事件、復選框點擊事件、this.header.events中的事件; * 觸發post-body、pre-body事件; * initServer(): * 觸發ajax事件(可以是用戶自定義的方法options.ajax),上傳數據格式為: * { * searchText:this.searchText, * sortName:this.options.sortName, * sortOrder:this.options.sortOrder, * pageSize/limit:..., * pageNumber/offset:..., * [filter]:..., * query:... * } * 上傳成功調用this.load方法,觸發load-success事件、上傳失敗load-error事件; * initSearchText(): * 初始化若設置搜索文本,開啟搜索,不支持本地數據搜索; * getCaret(): * getCaret改變排序點擊箭頭的上下方向; * updateSelected(): * 全選以及全不選時改變全選復選框的勾選狀態,以及tr行添加或刪除selected類; * updateRows(): * 復選框選中或撤銷選中后更新this.data數據中的[this.header.stateField]屬性,以便上傳復選框的狀態; * resetRows(): * 重置,撤銷復選框選中,以及data[i][that.header.stateField]賦值為false; * trigger(): * 執行this.options[BootstrapTable.EVENTS[name]]函數(類似瀏覽器默認事件),並觸發事件; * resetHeader(): * 一定時間內觸發this.fitHeader函數調整表頭的水平偏移,垂直滾動不影響表頭; * fitHeader(): * 克隆this.$el中的表頭,置入this.$tableHeader中,出使垂直滾動時,表頭信息不變; * 調整表體水平偏移量和表體水平一致; * resetFooter(): * 創建表尾,利用footerFormatter填充表尾內容,調用fitFooter調整表尾偏移; * fitFooter(): * 調整表尾水平偏移,設置表尾fnt-cell的寬度; * toggleColumn(): * toggleColumn篩選條目下拉菜單點選時更新columns[i].visible信息; * this.columns信息的改變,重新調用表頭、表體、搜索框、分頁初始化函數; * 當勾選的顯示條目小於this.options.minimumCountColumns時,勾選的條目設置disabled屬性; * toggleRow(): * 從表體中找到data-index=index或data-uniqueid=uniqueId那一行,根據visible顯示或隱藏; * getVisibleFields(): * 從this.column中剔除visible為false的項,返回field數組; */ var BootstrapTable = function (el, options) { this.options = options; this.$el = $(el); this.$el_ = this.$el.clone();// 記錄觸發元素的初始值,destroy銷毀重置的時候使用 this.timeoutId_ = 0;// 超時計時器,有滾動條的情況下調整表頭的水平偏移量 this.timeoutFooter_ = 0;// 超時計時器,有滾動條的情況下調整表尾的水平偏移量 this.init(); }; BootstrapTable.DEFAULTS = { classes: 'table table-hover',// 觸發元素table加入的樣式; locale: undefined,// 設置語言包; height: undefined,// 包括分頁和工具欄的高度; undefinedText: '-',// 無顯示文本時默認顯示內容; sortName: undefined, // 初始化排序字段名,須是column.filed主鍵名; // 點擊排序后更新options.sortName為被排序列的主鍵名columns[i].field; // 通過主鍵名在this.header.fields中的序號獲取sortName,比較后排序; sortOrder: 'asc',// 升序或降序,並且上傳 striped: false,// 觸發元素table是否顯示間行色 columns: [[]], data: [], dataField: 'rows',// 后台傳回data數據的字段名 method: 'get',// ajax發送類型 url: undefined,// ajax發送地址 ajax: undefined, // 用戶自定義ajax,或通過字符串調用window下的方法,對插件內配置有較多使用,調用其實不便 cache: true,// ajax設置 contentType: 'application/json', dataType: 'json', ajaxOptions: {}, queryParams: function (params) { return params; }, queryParamsType: 'limit', // undefined responseHandler: function (res) { return res; },// ajax處理相應的函數 pagination: false,// 分頁是否顯示 onlyInfoPagination: false,// 分頁文案提示只顯示有多少條數據 sidePagination: 'client', // client or server 前台分頁或后台分頁 totalRows: 0, // server side need to set pageNumber: 1,// 初始化顯示第幾頁 pageSize: 10,// 初始化頁面多少條數據 pageList: [10, 25, 50, 100],// 每頁顯示數據量切換配置項 paginationHAlign: 'right', //right, left 分頁浮動設置 paginationVAlign: 'bottom', //bottom, top, both // 分頁顯示位置,上、下或上下均顯示,默認底部顯示 // 設置一頁顯示多少條數據按鈕向上下拉,還是向下下拉,默認向上下拉 // 設置為both時,分頁在上下位置均顯示,設置一頁顯示多少條數據按鈕向上下拉 paginationDetailHAlign: 'left', //right, left 每頁幾行數據顯示區浮動情況 paginationPreText: '‹',// 分頁上一頁按鈕 paginationNextText: '›',// 分頁下一頁按鈕 search: false,// 是否支持搜索 searchOnEnterKey: false,// enter鍵開啟搜索 strictSearch: false,// 搜索框輸入內容是否須和條目顯示數據嚴格匹配,false時只要鍵入部分值就可獲得結果 searchAlign: 'right',// 搜索框對齊方式 selectItemName: 'btSelectItem',// 復選框默認上傳name值 showHeader: true,// 顯示表頭,包含標題欄內容 showFooter: false,// 默認隱藏表尾 showColumns: false,// 顯示篩選條目按鈕 showPaginationSwitch: false,// 顯示分頁隱藏展示按鈕 showRefresh: false,// 顯示刷新按鈕 showToggle: false,// 顯示切換表格顯示或卡片式詳情顯示按鈕 buttonsAlign: 'right',// 顯示隱藏分頁、刷新、切換表格或卡片顯示模式、篩選顯示條目、下載按鈕浮動設置 smartDisplay: true, // smartDisplay為真,當總頁數為1時,屏蔽分頁,以及下拉列表僅有一條時,屏蔽切換條目數按鈕下拉功能 escape: false,// 是否轉義 minimumCountColumns: 1,// 最小顯示條目數 idField: undefined,// data中存儲復選框value的鍵值 uniqueId: undefined,// 從data中獲取每行數據唯一標識的屬性名 cardView: false,// 是否顯示卡片式詳情(移動端),直接羅列每行信息,不以表格形式顯現 detailView: false,// 表格顯示數據時,每行數據前是否有點擊按鈕,顯示這行數據的卡片式詳情 detailFormatter: function (index, row) { return ''; },// 折疊式卡片詳情渲染文本,包含html標簽、Dom元素 trimOnSearch: true,// 搜索框鍵入值執行搜索時,清除兩端空格填入該搜索框 clickToSelect: false, singleSelect: false,// 復選框只能單選,需設置column.radio屬性為真 toolbar: undefined,// 用戶自定義按鈕組,區別於搜索框、分頁切換按鈕等 toolbarAlign: 'left',// 用戶自定義按鈕組浮動情況 checkboxHeader: true,// 為否隱藏全選按鈕 sortable: true,// 可排序全局設置 silentSort: true,// ajax交互的時候是否顯示loadding加載信息 maintainSelected: false,// 為真且翻頁時,保持前一頁各條row[that.header.stateField]為翻頁前的值 searchTimeOut: 500, // 搜索框鍵入值敲enter后隔多少時間執行搜索,使用clearTimeout避免間隔時間內多次鍵入反復搜索 searchText: '',// 初始化搜索內容 iconSize: undefined,// 按鈕、搜索輸入框通用大小,使用bootstrap的sm、md、lg等 iconsPrefix: 'glyphicon', // 按鈕通用樣式 icons: { paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',// 顯示分頁按鈕 paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',// 隱藏分頁按鈕 refresh: 'glyphicon-refresh icon-refresh',// 刷新按鈕 toggle: 'glyphicon-list-alt icon-list-alt',// 切換表格詳情顯示、卡片式顯示按鈕 columns: 'glyphicon-th icon-th',// 篩選條目按鈕 detailOpen: 'glyphicon-plus icon-plus',// 卡片式詳情展開按鈕 detailClose: 'glyphicon-minus icon-minus'// 卡片式詳情折疊按鈕 },// 工具欄按鈕具體樣式 rowStyle: function (row, index) { return {}; },// 傳遞給每一行的css設置,row為這一行的data數據 rowAttributes: function (row, index) { return {}; },// 傳遞給每一行的屬性設置 onAll: function (name, args) { return false; }, onClickCell: function (field, value, row, $element) { return false; }, onDblClickCell: function (field, value, row, $element) { return false; }, onClickRow: function (item, $element) { return false; }, onDblClickRow: function (item, $element) { return false; }, onSort: function (name, order) { return false; }, onCheck: function (row) { return false; }, onUncheck: function (row) { return false; }, onCheckAll: function (rows) { return false; }, onUncheckAll: function (rows) { return false; }, onCheckSome: function (rows) { return false; }, onUncheckSome: function (rows) { return false; }, onLoadSuccess: function (data) { return false; }, onLoadError: function (status) { return false; }, onColumnSwitch: function (field, checked) { return false; }, onPageChange: function (number, size) { return false; }, onSearch: function (text) { return false; }, onToggle: function (cardView) { return false; }, onPreBody: function (data) { return false; }, onPostBody: function () { return false; }, onPostHeader: function () { return false; }, onExpandRow: function (index, row, $detail) { return false; }, onCollapseRow: function (index, row) { return false; }, onRefreshOptions: function (options) { return false; }, onResetView: function () { return false; } }; BootstrapTable.LOCALES = []; BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES['en'] = { formatLoadingMessage: function () { return 'Loading, please wait...'; }, formatRecordsPerPage: function (pageNumber) { return sprintf('%s records per page', pageNumber); },// 每頁顯示條目數提示文案 formatShowingRows: function (pageFrom, pageTo, totalRows) { return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows); },// 分頁提示當前頁從第pageFrom到pageTo,總totalRows條 formatDetailPagination: function (totalRows) { return sprintf('Showing %s rows', totalRows);// 分頁提示供多少條數據 }, formatSearch: function () { return 'Search'; },// 設置搜索框placeholder屬性 formatNoMatches: function () { return 'No matching records found'; },// 沒有數據時提示文案 formatPaginationSwitch: function () { return 'Hide/Show pagination'; },// 顯示隱藏分頁按鈕title屬性提示文案 formatRefresh: function () { return 'Refresh'; },// 刷新按鈕title屬性提示文案 formatToggle: function () { return 'Toggle'; },// 切換表格、卡片顯示模式按鈕title屬性提示文案 formatColumns: function () { return 'Columns'; },// 篩選顯示條目按鈕title屬性提示文案 formatAllRows: function () { return 'All'; } }; $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']); BootstrapTable.COLUMN_DEFAULTS = { radio: false,// 有否radio,有則options.singleSelect設為真 checkbox: false,// 有否checkbox,options.singleSelect設為真,checkbox單選 checkboxEnabled: true,// 復選框是否可選 field: undefined,// 后台數據的id號 title: undefined,// 內容文案 titleTooltip: undefined,// title屬性文案 'class': undefined,// 樣式 align: undefined, // tbody、thead、tfoot文本對齊情況 halign: undefined, // thead文本對齊情況 falign: undefined, // tfoot文本對齊情況 valign: undefined, // 垂直對齊情況 width: undefined, // 寬度,字符串或數值輸入,均轉化為"36px"或"10%"形式 sortable: false,// 是否可排序,options.sortable設置為真的時候可用 order: 'asc', // asc, desc visible: true,// 可見性 switchable: true,// 該條目可以通過篩選條目按鈕切換顯示狀態 clickToSelect: true, formatter: undefined, // 以function(field,row,index){}格式化數據,field后台字段,row行數據,index對應row的序號值 // 無配置時以title顯示,有配置時以返回值顯示 footerFormatter: undefined,// 填充表尾內容 events: undefined,// 數據格式為[{"click element":functionName}],回調中傳入(value,row,index) sorter: undefined,// 調用sorter函數或window[sorter]函數進行排序,高優先級 sortName: undefined,// 進行排序的字段名,用以獲取options.data中的數據 cellStyle: undefined, // 調用cellStyle函數或window[cellStyle]函數添加樣式以及類; // 以function(field,row,index){}設置單元格樣式以及樣式類,返回數據格式為{classes:"class1 class2",css:{key:value}} searchable: true,// 設置哪一列的數據元素可搜索 searchFormatter: true, cardVisible: true// 設為否時,卡片式顯示時該列數據不顯示 }; BootstrapTable.EVENTS = { 'all.bs.table': 'onAll', 'click-cell.bs.table': 'onClickCell', 'dbl-click-cell.bs.table': 'onDblClickCell', 'click-row.bs.table': 'onClickRow', 'dbl-click-row.bs.table': 'onDblClickRow', 'sort.bs.table': 'onSort', 'check.bs.table': 'onCheck', 'uncheck.bs.table': 'onUncheck', 'check-all.bs.table': 'onCheckAll', 'uncheck-all.bs.table': 'onUncheckAll', 'check-some.bs.table': 'onCheckSome', 'uncheck-some.bs.table': 'onUncheckSome', 'load-success.bs.table': 'onLoadSuccess', 'load-error.bs.table': 'onLoadError', 'column-switch.bs.table': 'onColumnSwitch', 'page-change.bs.table': 'onPageChange', 'search.bs.table': 'onSearch', 'toggle.bs.table': 'onToggle', 'pre-body.bs.table': 'onPreBody', 'post-body.bs.table': 'onPostBody', 'post-header.bs.table': 'onPostHeader', 'expand-row.bs.table': 'onExpandRow', 'collapse-row.bs.table': 'onCollapseRow', 'refresh-options.bs.table': 'onRefreshOptions', 'reset-view.bs.table': 'onResetView' }; BootstrapTable.prototype.init = function () { this.initLocale(); // 將語言包添加進配置項this.options中,數據格式是{formatLoadingMessage:fn}; this.initContainer(); // 創建包裹元素this.container及其子元素this.$toolbar、this.$pagination等,為表格添加樣式; this.initTable(); // 獲取頁面配置更新options.columns、options.data,this.columns記錄表體對應標題欄的數據; this.initHeader(); // 渲染表頭,設置this.header數據記錄主鍵等,綁定表頭事件,卡片式顯示時隱藏表頭; this.initData(); // 頁面初始化、后台傳值、表頭表尾插入數據,更新this.data、options.data,前台分頁則排序; this.initFooter(); // 顯示隱藏表尾; this.initToolbar(); // 創建工具欄按鈕組,並綁定事件; this.initPagination(); // 創建分頁相關內容,並綁定事件; this.initBody(); // 渲染表體,區分卡片顯示和表格顯示兩類,綁定相關事件; this.initSearchText(); // 初始化若設置搜索文本,開啟搜索,不支持本地數據搜索; this.initServer(); // 上傳數據,成功時調用load方法渲染表格; }; // 將語言包添加進配置項this.options中,數據格式是{formatLoadingMessage:fn}; BootstrapTable.prototype.initLocale = function () { if (this.options.locale) { var parts = this.options.locale.split(/-|_/); parts[0].toLowerCase(); parts[1] && parts[1].toUpperCase(); if ($.fn.bootstrapTable.locales[this.options.locale]) { $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]); } else if ($.fn.bootstrapTable.locales[parts.join('-')]) { $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]); } else if ($.fn.bootstrapTable.locales[parts[0]]) { $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]); } } }; // 創建包裹元素this.container及其子元素this.$toolbar、this.$pagination等,為表格添加樣式; BootstrapTable.prototype.initContainer = function () { this.$container = $([ '<div class="bootstrap-table">', '<div class="fixed-table-toolbar"></div>', this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ? '<div class="fixed-table-pagination" style="clear: both;"></div>' : '', '<div class="fixed-table-container">', '<div class="fixed-table-header"><table></table></div>', '<div class="fixed-table-body">', '<div class="fixed-table-loading">', this.options.formatLoadingMessage(), '</div>', '</div>', '<div class="fixed-table-footer"><table><tr></tr></table></div>', this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ? '<div class="fixed-table-pagination"></div>' : '', '</div>', '</div>' ].join('')); this.$container.insertAfter(this.$el); this.$tableContainer = this.$container.find('.fixed-table-container'); this.$tableHeader = this.$container.find('.fixed-table-header'); this.$tableBody = this.$container.find('.fixed-table-body'); this.$tableLoading = this.$container.find('.fixed-table-loading'); this.$tableFooter = this.$container.find('.fixed-table-footer'); this.$toolbar = this.$container.find('.fixed-table-toolbar'); this.$pagination = this.$container.find('.fixed-table-pagination'); this.$tableBody.append(this.$el); this.$container.after('<div class="clearfix"></div>'); this.$el.addClass(this.options.classes); if (this.options.striped) { this.$el.addClass('table-striped'); } if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) { this.$tableContainer.addClass('table-no-bordered'); } }; // 當html中包含thead>tr>th以及tbody>tr>td時,獲取頁面的配置項更新options.columns、options.data; // js配置的優先級高於html頁面配置; // this.columns以this.columns[fieldIndex]的數組形式[columns]記錄表體相應標題欄的數據內容; BootstrapTable.prototype.initTable = function () { var that = this, columns = [], data = []; // 觸發元素table中有thead子標簽等則使用(查詢排序的時候),無則創建 this.$header = this.$el.find('>thead'); if (!this.$header.length) { this.$header = $('<thead></thead>').appendTo(this.$el); } this.$header.find('tr').each(function () { var column = []; $(this).find('th').each(function () { column.push($.extend({}, { title: $(this).html(), 'class': $(this).attr('class'), titleTooltip: $(this).attr('title'), rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined, colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined }, $(this).data())); }); columns.push(column); }); if (!$.isArray(this.options.columns[0])) { this.options.columns = [this.options.columns];// 都處理成兩維數組的形式 } this.options.columns = $.extend(true, [], columns, this.options.columns); // 借用this.columns[fieldIndex]=column構建this.columns; // this.column的數據格式為{[column]},列坐標相同的標題欄取靠后的子標題; // 意義:填充表體內容時,this.column提供每列數據的相關信息; this.columns = []; // setFieldIndex將標題欄的fieldIndex屬性賦值為標題欄所在列坐標; setFieldIndex(this.options.columns); $.each(this.options.columns, function (i, columns) { $.each(columns, function (j, column) { column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column); if (typeof column.fieldIndex !== 'undefined') { that.columns[column.fieldIndex] = column; } that.options.columns[i][j] = column; }); }); if (this.options.data.length) { return; } this.$el.find('>tbody>tr').each(function () { var row = {}; // 獲取每一行tr的id、class、data屬性,以數組形式賦值給data row._id = $(this).attr('id'); row._class = $(this).attr('class'); row._data = getRealDataAttr($(this).data()); // 獲取某一行每個子元素的內容、id、class、rowspan、title、data屬性 $(this).find('td').each(function (i) { // field通常是后台數據的id號,沒有該值的時候賦值為column列坐標信息,寫入本地數據的時候 var field = that.columns[i].field; row[field] = $(this).html(); // save td's id, class and data-* attributes row['_' + field + '_id'] = $(this).attr('id'); row['_' + field + '_class'] = $(this).attr('class'); row['_' + field + '_rowspan'] = $(this).attr('rowspan'); row['_' + field + '_title'] = $(this).attr('title'); row['_' + field + '_data'] = getRealDataAttr($(this).data()); }); data.push(row); }); this.options.data = data; }; // 由options.columns渲染表頭,th的data-field記為column[field],data數據記為column; // 更新this.header記錄主鍵、樣式、事件、格式化函數等,以及stateField復選框上傳字段; // 綁定事件,包括點擊排序、確認鍵排序、全選,更新上傳數據、頁面狀態等; BootstrapTable.prototype.initHeader = function () { var that = this, visibleColumns = {}, html = []; this.header = { fields: [], styles: [], classes: [], formatters: [], events: [], sorters: [], sortNames: [], cellStyles: [], searchables: [] }; $.each(this.options.columns, function (i, columns) { html.push('<tr>'); // 頁面以表格顯示且有卡片式詳情點擊按鈕的時候,表頭首列為該按鈕開辟一個空白的單元格 if (i == 0 && !that.options.cardView && that.options.detailView) { html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>', that.options.columns.length)); } $.each(columns, function (j, column) { var text = '', halign = '', align = '', style = '', class_ = sprintf(' class="%s"', column['class']), order = that.options.sortOrder || column.order, unitWidth = 'px', width = column.width; // width輸入寬度有%或px時,分割%或px到unitWidth中,width保留數字字符串 // width輸入數值時,unitWidth默認取px if (column.width !== undefined && (!that.options.cardView)) { if (typeof column.width === 'string') { if (column.width.indexOf('%') !== -1) { unitWidth = '%'; } } } if (column.width && typeof column.width === 'string') { width = column.width.replace('%', '').replace('px', ''); } halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align); align = sprintf('text-align: %s; ', column.align); style = sprintf('vertical-align: %s; ', column.valign); style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ? '36px' : (width ? width + unitWidth : undefined)); /** * this.header.styles、this.header.classes: * 數組形式存儲經過處理的每列數據的樣式、類; * this.header.formatters、this.header.cellStyles、this.header.sorters: * 數組形式存儲格式化函數、設置單元格樣式函數、排序函數,或者window方法名; * this.header.events、this.header.sortNames、this.header.searchables: * 數組形式存儲表體相應標題欄配置的事件events、上傳排序的字段名sortName、可搜索searchable; */ // 填充觸發元素的tbody內容塊時使用 if (typeof column.fieldIndex !== 'undefined') { that.header.fields[column.fieldIndex] = column.field; that.header.styles[column.fieldIndex] = align + style; that.header.classes[column.fieldIndex] = class_; that.header.formatters[column.fieldIndex] = column.formatter; that.header.events[column.fieldIndex] = column.events; that.header.sorters[column.fieldIndex] = column.sorter; that.header.sortNames[column.fieldIndex] = column.sortName; that.header.cellStyles[column.fieldIndex] = column.cellStyle; that.header.searchables[column.fieldIndex] = column.searchable; if (!column.visible) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } visibleColumns[column.field] = column; } // options.columns數據回顯和渲染頁面 html.push('<th' + sprintf(' title="%s"', column.titleTooltip), column.checkbox || column.radio ? sprintf(' class="bs-checkbox %s"', column['class'] || '') : class_, sprintf(' style="%s"', halign + style), sprintf(' rowspan="%s"', column.rowspan), sprintf(' colspan="%s"', column.colspan), sprintf(' data-field="%s"', column.field), "tabindex='0'", '>'); html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ? 'sortable both' : '')); text = column.title; if (column.checkbox) { if (!that.options.singleSelect && that.options.checkboxHeader) { text = '<input name="btSelectAll" type="checkbox" />'; } that.header.stateField = column.field;// 復選框內容上傳時的字段名 } if (column.radio) { text = ''; that.header.stateField = column.field; that.options.singleSelect = true; } html.push(text); html.push('</div>'); html.push('<div class="fht-cell"></div>'); html.push('</div>'); html.push('</th>'); }); html.push('</tr>'); }); this.$header.html(html.join('')); this.$header.find('th[data-field]').each(function (i) { // 標題欄data屬性寫入各自的column數據,展開卡片式詳情時使用 $(this).data(visibleColumns[$(this).data('field')]); }); // 綁定點擊排序事件 this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) { var target = $(this); if (target.closest('.bootstrap-table')[0] !== that.$container[0]) return false; if (that.options.sortable && target.parent().data().sortable) { that.onSort(event); } }); // 確認鍵排序 this.$header.children().children().off('keypress').on('keypress', function (event) { if (that.options.sortable && $(this).data().sortable) { var code = event.keyCode || event.which; if (code == 13) { //Enter keycode that.onSort(event); } } }); // 顯示隱藏表頭,調整this.$tableLoading位置;options.cardView為真時卡片式顯示隱藏表頭 if (!this.options.showHeader || this.options.cardView) { this.$header.hide(); this.$tableHeader.hide(); this.$tableLoading.css('top', 0); } else { this.$header.show(); this.$tableHeader.show(); this.$tableLoading.css('top', this.$header.outerHeight() + 1); this.getCaret();// 更新排序箭頭顯示情況 } // 全選 this.$selectAll = this.$header.find('[name="btSelectAll"]'); this.$selectAll.off('click').on('click', function () { var checked = $(this).prop('checked'); that[checked ? 'checkAll' : 'uncheckAll']();// 改變復選框勾選狀態,更新上傳數據 that.updateSelected();// tr添加selected類 }); }; // 顯示隱藏表尾 BootstrapTable.prototype.initFooter = function () { if (!this.options.showFooter || this.options.cardView) { this.$tableFooter.hide(); } else { this.$tableFooter.show(); } }; // 頁面初始化時this.data賦值為this.options.data; // ajax交互時this.data賦值為后台返回的數據,options.data也同樣更新為后台返回的數據; // type為append時,表格尾部插入數據,this.data、options.data尾部插入相應數據; // type為prepend時,表格頂部插入數據,this.data、options.data頭部插入相應數據; // 前台分頁的情況下調用this.initSort,后台分頁以返回數據為准; BootstrapTable.prototype.initData = function (data, type) { if (type === 'append') { this.data = this.data.concat(data); } else if (type === 'prepend') { this.data = [].concat(data).concat(this.data); } else { this.data = data || this.options.data; } if (type === 'append') { this.options.data = this.options.data.concat(data); } else if (type === 'prepend') { this.options.data = [].concat(data).concat(this.options.data); } else { this.options.data = this.data; } if (this.options.sidePagination === 'server') { return; } this.initSort(); }; // onSort方法設置點擊排序按鈕時,更新options.sortName為相應標題欄column.field值; // initSort由column.field值獲得相應的sortName; // 調用option.sorter函數或window[option.sorter]方法進行比較排序; // 或者直接比較data[sortName]進行排序; // 排序通過更新this.data數據實現,this.data渲染到頁面使用initBody方法; BootstrapTable.prototype.initSort = function () { var that = this, name = this.options.sortName, order = this.options.sortOrder === 'desc' ? -1 : 1, index = $.inArray(this.options.sortName, this.header.fields); if (index !== -1) { this.data.sort(function (a, b) { if (that.header.sortNames[index]) { name = that.header.sortNames[index];// 獲取colum.sortName } // 獲取每行數據的data[sortName]的值,轉義后返回 var aa = getItemField(a, name, that.options.escape), bb = getItemField(b, name, that.options.escape), // 調用column.sorter函數或window[column.sorter]方法進行比較,上下文是that.header value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]); if (value !== undefined) { return order * value; } if (aa === undefined || aa === null) { aa = ''; } if (bb === undefined || bb === null) { bb = ''; } if ($.isNumeric(aa) && $.isNumeric(bb)) { aa = parseFloat(aa); bb = parseFloat(bb); if (aa < bb) { return order * -1; } return order; } if (aa === bb) { return 0; } if (typeof aa !== 'string') { aa = aa.toString(); } if (aa.localeCompare(bb) === -1) {//bb為何不要轉換? return order * -1; } return order; }); } }; // 點擊排序時更新options.sortName為被排序列數據對應column[field]值,以便initSort獲取sortName; // 更新options.sortOrder為被排序列數據對應column[order]值,或保持原有值; // 觸發sort事件,調用initServer獲取后台數據,調用initSort排序、initBody渲染表體; BootstrapTable.prototype.onSort = function (event) { var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(), $this_ = this.$header.find('th').eq($this.index());// 記錄this.$header下相同元素 this.$header.add(this.$header_).find('span.order').remove(); // options.sortName更新被排序列數據對應column[field]值,以便initSort獲取sortName加以比較; if (this.options.sortName === $this.data('field')) { this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc'; } else { this.options.sortName = $this.data('field'); this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc'; } this.trigger('sort', this.options.sortName, this.options.sortOrder); $this.add($this_).data('order', this.options.sortOrder); this.getCaret();// 更新排序箭頭樣式 if (this.options.sidePagination === 'server') { this.initServer(this.options.silentSort); return; } this.initSort(); this.initBody(); }; // 創建工具欄內的用戶自定義按鈕組、分頁顯示隱藏切換按鈕、刷新按鈕、篩選條目按鈕 // 以及卡片表格顯示切換按鈕、搜索框,並綁定相應事件; // 篩選條目時觸發column-switch事件; BootstrapTable.prototype.initToolbar = function () { var that = this, html = [], timeoutId = 0, $keepOpen, $search, switchableCount = 0; if (this.$toolbar.find('.bars').children().length) { $('body').append($(this.options.toolbar)); } this.$toolbar.html(''); if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') { $(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign)) .appendTo(this.$toolbar) .append($(this.options.toolbar)); // $(this.options.toolbar)引用對象形式,只會在頁面上創建一次 } html = [sprintf('<div class="columns columns-%s btn-group pull-%s">', this.options.buttonsAlign, this.options.buttonsAlign)]; if (typeof this.options.icons === 'string') { // 調用window[options.icons]函數顯示按鈕列表 this.options.icons = calculateObjectValue(null, this.options.icons); } // 顯示隱藏分頁按鈕 if (this.options.showPaginationSwitch) { html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">', this.options.formatPaginationSwitch()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown), '</button>'); } // 刷新按鈕 if (this.options.showRefresh) { html.push(sprintf('<button class="btn btn-default' + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="refresh" title="%s">', this.options.formatRefresh()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh), '</button>'); } // 卡片式顯示或表格詳情顯示切換按鈕 if (this.options.showToggle) { html.push(sprintf('<button class="btn btn-default' + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="toggle" title="%s">', this.options.formatToggle()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle), '</button>'); } // 篩選條目按鈕,並創建下拉列表 if (this.options.showColumns) { html.push(sprintf('<div class="keep-open btn-group" title="%s">', this.options.formatColumns()), '<button type="button" class="btn btn-default' + sprintf(' btn-%s', this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">', sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns), ' <span class="caret"></span>', '</button>', '<ul class="dropdown-menu" role="menu">'); $.each(this.columns, function (i, column) { if (column.radio || column.checkbox) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } var checked = column.visible ? ' checked="checked"' : ''; if (column.switchable) { html.push(sprintf('<li>' + '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' + '</li>', column.field, i, checked, column.title)); switchableCount++; } }); html.push('</ul>', '</div>'); } html.push('</div>'); if (this.showToolbar || html.length > 2) { this.$toolbar.append(html.join('')); } // 綁定分頁顯示隱藏按鈕點擊事件 if (this.options.showPaginationSwitch) { this.$toolbar.find('button[name="paginationSwitch"]') .off('click').on('click', $.proxy(this.togglePagination, this)); } // 綁定刷新按鈕點擊事件 if (this.options.showRefresh) { this.$toolbar.find('button[name="refresh"]') .off('click').on('click', $.proxy(this.refresh, this)); } // 綁定卡片式顯示、表格詳情顯示切換按鈕點擊事件 if (this.options.showToggle) { this.$toolbar.find('button[name="toggle"]') .off('click').on('click', function () { that.toggleView(); }); } // 幫點篩選條目下拉列表中復選框的點擊事件,篩選條目按鈕點擊事件由bootstrap提供 if (this.options.showColumns) { $keepOpen = this.$toolbar.find('.keep-open'); if (switchableCount <= this.options.minimumCountColumns) { $keepOpen.find('input').prop('disabled', true); } $keepOpen.find('li').off('click').on('click', function (event) { event.stopImmediatePropagation();// 阻止事件冒泡,並阻止同類型事件的冒泡 }); $keepOpen.find('input').off('click').on('click', function () { var $this = $(this); that.toggleColumn(getFieldIndex(that.columns, $(this).data('field')), $this.prop('checked'), false); that.trigger('column-switch', $(this).data('field'), $this.prop('checked')); }); } // 創建搜索框,並綁定搜索事件 if (this.options.search) { html = []; html.push( '<div class="pull-' + this.options.searchAlign + ' search">', sprintf('<input class="form-control' + sprintf(' input-%s', this.options.iconSize) + '" type="text" placeholder="%s">', this.options.formatSearch()), '</div>'); this.$toolbar.append(html.join('')); $search = this.$toolbar.find('.search input'); $search.off('keyup drop').on('keyup drop', function (event) { if (that.options.searchOnEnterKey) { if (event.keyCode !== 13) { return; } } clearTimeout(timeoutId); timeoutId = setTimeout(function () { that.onSearch(event); }, that.options.searchTimeOut); }); if (isIEBrowser()) { $search.off('mouseup').on('mouseup', function (event) { clearTimeout(timeoutId); timeoutId = setTimeout(function () { that.onSearch(event); }, that.options.searchTimeOut); }); } } }; // this.text,this.options.text設為搜索框去除兩端空白的值,pageNumber設為1; // 調用initSearch將篩選本地數據;調用updatePagination完成遠程交互或單渲染本地數據; // 觸發search事件; BootstrapTable.prototype.onSearch = function (event) { var text = $.trim($(event.currentTarget).val()); if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) { $(event.currentTarget).val(text); } if (text === this.searchText) { return; } this.searchText = text; this.options.searchText = text; this.options.pageNumber = 1; this.initSearch(); this.updatePagination(); this.trigger('search', text); }; // 前台分頁的情況下,先通過this.filterColumns通過this.option.data過濾this.data數據; // 再通過搜索文本過濾this.data數據; // 輸入文本和經this.header.formatters或window[this.header.formatters]函數格式化匹配比對; BootstrapTable.prototype.initSearch = function () { var that = this; if (this.options.sidePagination !== 'server') { var s = this.searchText && this.searchText.toLowerCase(); var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns; // options.data和this.filterColumns相符則在this.data中保留,不相符則在this.data中刪除 this.data = f ? $.grep(this.options.data, function (item, i) { for (var key in f) { if ($.isArray(f[key])) { if ($.inArray(item[key], f[key]) === -1) { return false; } } else if (item[key] !== f[key]) { return false; } } return true; }) : this.options.data; // 在前台分頁的情況下檢索數據,使用$.grep返回篩選后的數組內容 this.data = s ? $.grep(this.data, function (item, i) { for (var key in item) { key = $.isNumeric(key) ? parseInt(key, 10) : key; var value = item[key],//data[key] // 當key為field時,getFieldIndex獲取相應列條目數據fieldIndex值,否則返回-1 // 問題,可以設置if語句排除key不等於field的情況,j和index等值 column = that.columns[getFieldIndex(that.columns, key)], j = $.inArray(key, that.header.fields); if (column && column.searchFormatter) { value = calculateObjectValue(column, that.header.formatters[j], [value, item, i], value); } var index = $.inArray(key, that.header.fields); if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) { if (that.options.strictSearch) { if ((value + '').toLowerCase() === s) { return true; } } else { if ((value + '').toLowerCase().indexOf(s) !== -1) { return true; } } } } return false; }) : this.data; } }; // 初始化設置分頁相關頁面信息顯示情況,包括當前頁顯示第幾條到第幾天數據,共幾條數據,每頁顯示幾條數據; // 以及每頁顯示數據量切換按鈕,選擇頁面的分頁欄顯示情況,再綁定事件; // 通過options.pageNumber獲取this.pageFrom、this.pageTo,以便前台分頁時initBody獲取相應數據; BootstrapTable.prototype.initPagination = function () { if (!this.options.pagination) { this.$pagination.hide(); return; } else { this.$pagination.show(); } var that = this, html = [], $allSelected = false,// 為真時,顯示所有數據條目,同時顯示數據量切換按鈕文本改為options.formatAllRows() i, from, to, $pageList, $first, $pre, $next, $last, $number, data = this.getData(); if (this.options.sidePagination !== 'server') { this.options.totalRows = data.length;// 數據總條數 } // this.options.totalRows數據總條數; // this.options.pageSize一頁顯示幾條數據,顯示數據量切換按鈕默認文本; // this.totalPages總頁數,與this.options.totalPages似沒有差別,疑為插件作者未調優代碼; // this.options.totalPages總頁數; // this.options.pageNumber當前頁頁碼; // this.pageFrom當前頁從總數據的第幾條開始; // this.pageTo當前頁到總數據的第幾條為止; if (this.options.totalRows) { // 當options.pageSize和options.formatAllRows()相同時,意味顯示所有條目 // 或者options.pageSize即為options.totalRows總條目數,且options.formatAllRows()在pageList設置中 // $allSelected記為真,頁面顯示數據量切換按鈕的顯示文本為options.formatAllRows() if (this.options.pageSize === this.options.formatAllRows()) { this.options.pageSize = this.options.totalRows; $allSelected = true; } else if (this.options.pageSize === this.options.totalRows) { var pageLst = typeof this.options.pageList === 'string' ? this.options.pageList.replace('[', '').replace(']', '') .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList;// 每頁顯示數據條數列表項 if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) { $allSelected = true; } } this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1; // -1針對this.options.totalRows是this.options.pageSize倍數的情況 this.options.totalPages = this.totalPages; } if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) { this.options.pageNumber = this.totalPages; } this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1; this.pageTo = this.options.pageNumber * this.options.pageSize; if (this.pageTo > this.options.totalRows) { this.pageTo = this.options.totalRows; } // 分頁提示文案,即總共包含幾條數據,或當前頁從第幾條到第幾條 html.push( '<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">', '<span class="pagination-info">', this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) : this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows), '</span>'); if (!this.options.onlyInfoPagination) { html.push('<span class="page-list">'); // 分頁提示文案,即每頁顯示幾條數據,每頁顯示數據量下拉列表 var pageNumber = [ sprintf('<span class="btn-group %s">', this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ? 'dropdown' : 'dropup'), '<button type="button" class="btn btn-default ' + sprintf(' btn-%s', this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">', '<span class="page-size">', $allSelected ? this.options.formatAllRows() : this.options.pageSize, '</span>', ' <span class="caret"></span>', '</button>', '<ul class="dropdown-menu" role="menu">' ], pageList = this.options.pageList; // 每頁切換條目數下拉列表實現 if (typeof this.options.pageList === 'string') { var list = this.options.pageList.replace('[', '').replace(']', '') .replace(/ /g, '').split(','); pageList = []; $.each(list, function (i, value) { pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ? that.options.formatAllRows() : +value); }); } $.each(pageList, function (i, page) { // this.options.smartDisplay為真,當總頁數為1時,屏蔽分頁,以及下拉列表僅有一條時,屏蔽切換條目數按鈕下拉功能 if (!that.options.smartDisplay || i === 0 || pageList[i - 1] <= that.options.totalRows) { var active; if ($allSelected) { active = page === that.options.formatAllRows() ? ' class="active"' : ''; } else { active = page === that.options.pageSize ? ' class="active"' : ''; } pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page)); } }); pageNumber.push('</ul></span>'); html.push(this.options.formatRecordsPerPage(pageNumber.join(''))); html.push('</span>'); // 分頁 // 策略:通過from初始頁、to結尾頁,先設置首頁起的顯示情況,再設置...按鈕的顯示情況,接着尾頁的顯示情況 // 順序設置,由一般到具體 html.push('</div>', '<div class="pull-' + this.options.paginationHAlign + ' pagination">', '<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">', '<li class="page-pre"><a href="javascript:void(0)">' + this.options.paginationPreText + '</a></li>'); if (this.totalPages < 5) { from = 1; to = this.totalPages; } else { from = this.options.pageNumber - 2; to = from + 4; if (from < 1) { from = 1; to = 5; } if (to > this.totalPages) { to = this.totalPages; from = to - 4; } } // 總頁數大於6時,顯示第一頁,最后一頁,pageNumber--,pageNumber,pageNumber++,以及兩串... if (this.totalPages >= 6) { if (this.options.pageNumber >= 3) { html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">', '<a href="javascript:void(0)">', 1, '</a>', '</li>'); from++; } if (this.options.pageNumber >= 4) { // from--顯示第二頁按鈕 if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) { from--; } else { html.push('<li class="page-first-separator disabled">', '<a href="javascript:void(0)">...</a>', '</li>'); } to--; } } // 根據上一條if語句form++的情況,pageNumber臨近尾頁的時候執行from--,顯示后五條 if (this.totalPages >= 7) { if (this.options.pageNumber >= (this.totalPages - 2)) { from--; } } // 根據上一條if語句to--的情況,pageNumber挨近尾頁的時候執行to--,顯示后五條 if (this.totalPages == 6) { if (this.options.pageNumber >= (this.totalPages - 2)) { to++; } } else if (this.totalPages >= 7) { if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) { to++; } } for (i = from; i <= to; i++) { html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">', '<a href="javascript:void(0)">', i, '</a>', '</li>'); } if (this.totalPages >= 8) { if (this.options.pageNumber <= (this.totalPages - 4)) { html.push('<li class="page-last-separator disabled">', '<a href="javascript:void(0)">...</a>', '</li>'); } } if (this.totalPages >= 6) { if (this.options.pageNumber <= (this.totalPages - 3)) { html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">', '<a href="javascript:void(0)">', this.totalPages, '</a>', '</li>'); } } html.push( '<li class="page-next"><a href="javascript:void(0)">' + this.options.paginationNextText + '</a></li>', '</ul>', '</div>'); } this.$pagination.html(html.join('')); if (!this.options.onlyInfoPagination) { $pageList = this.$pagination.find('.page-list a');// 每頁顯示數據量切換按鈕 $first = this.$pagination.find('.page-first'); $pre = this.$pagination.find('.page-pre'); $next = this.$pagination.find('.page-next'); $last = this.$pagination.find('.page-last'); $number = this.$pagination.find('.page-number'); if (this.options.smartDisplay) { if (this.totalPages <= 1) { this.$pagination.find('div.pagination').hide(); } if (pageList.length < 2 || this.options.totalRows <= pageList[0]) { this.$pagination.find('span.page-list').hide(); } this.$pagination[this.getData().length ? 'show' : 'hide'](); } if ($allSelected) { this.options.pageSize = this.options.formatAllRows(); } // 綁定事件 $pageList.off('click').on('click', $.proxy(this.onPageListChange, this)); $first.off('click').on('click', $.proxy(this.onPageFirst, this)); $pre.off('click').on('click', $.proxy(this.onPagePre, this)); $next.off('click').on('click', $.proxy(this.onPageNext, this)); $last.off('click').on('click', $.proxy(this.onPageLast, this)); $number.off('click').on('click', $.proxy(this.onPageNumber, this)); } }; // 分頁點選按鈕有disabled屬性則返回,無則重新布局分頁顯示面板; // maintainSelected為否時,調用resetRows重置復選框為不選中,調用initServer交互或initbody渲染頁面; // initSever由后台返回數據; // initPagination通過options.pageNumber取得options.pageFrom、options.pageTo; // initBody由options.pageFrom、options.pageTo獲取需要渲染的數據data; // 觸發page-change事件; BootstrapTable.prototype.updatePagination = function (event) { // Fix #171: IE disabled button can be clicked bug. if (event && $(event.currentTarget).hasClass('disabled')) { return; } if (!this.options.maintainSelected) { this.resetRows(); } this.initPagination(); if (this.options.sidePagination === 'server') { this.initServer(); } else { this.initBody(); } this.trigger('page-change', this.options.pageNumber, this.options.pageSize); }; // 每頁顯示數據量下拉列表選中時觸發,替換每頁顯示數據量按鈕文本; // 更新options.pageSize,通過updatePagination調用initPagination設置this.pageFrom、this.pageTo; // updatePagination再調用initServer完成交互,或initBody渲染本地數據; BootstrapTable.prototype.onPageListChange = function (event) { var $this = $(event.currentTarget); $this.parent().addClass('active').siblings().removeClass('active'); this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ? this.options.formatAllRows() : +$this.text(); this.$toolbar.find('.page-size').text(this.options.pageSize); this.updatePagination(event); }; // 更新options.pageNumber,通過updatePagination調用initPagination設置this.pageFrom、this.pageTo; // updatePagination再調用initServer完成交互,或initBody渲染本地數據; // 跳轉分頁首頁 BootstrapTable.prototype.onPageFirst = function (event) { this.options.pageNumber = 1; this.updatePagination(event); }; // 跳轉分頁上一頁 BootstrapTable.prototype.onPagePre = function (event) { if ((this.options.pageNumber - 1) == 0) { this.options.pageNumber = this.options.totalPages; } else { this.options.pageNumber--; } this.updatePagination(event); }; // 跳轉分頁下一頁 BootstrapTable.prototype.onPageNext = function (event) { if ((this.options.pageNumber + 1) > this.options.totalPages) { this.options.pageNumber = 1; } else { this.options.pageNumber++; } this.updatePagination(event); }; // 跳轉尾頁 BootstrapTable.prototype.onPageLast = function (event) { this.options.pageNumber = this.totalPages; this.updatePagination(event); }; // 由頁碼跳轉 BootstrapTable.prototype.onPageNumber = function (event) { if (this.options.pageNumber === +$(event.currentTarget).text()) { return; } this.options.pageNumber = +$(event.currentTarget).text(); this.updatePagination(event); }; // fixedScroll為否的情況下,表體移動到頂部; // 通過this.pageFrom、this.pageTo截取this.getData()數據row渲染表體,主要是tbody>tr以及tbody>tr>td; // tbody>tr的data-index設為行號,class、id為row._class、row._id,樣式、data數據通過調用函數獲得; // tbody>tr>td區分為卡片顯示和表格顯示兩類,顯示值取經this.header.formatters[i]處理后的row[field]; // tbody>tr>td其他class、id、title、data取row[_field_class]等; // 綁定展開卡片詳情按鈕點擊事件、復選框點擊事件、this.header.events中的事件; // 觸發post-body、pre-body事件; BootstrapTable.prototype.initBody = function (fixedScroll) { var that = this, html = [], data = this.getData();// 獲取搜索過濾后的數據 // data的數據格式為對象形式 // [{ // 行tr中的屬性設置 // _data:{ // index:1,// 后續會自動賦值為數據在當前頁的所在行號 // field:field // }, // _id:id, // _class:class, // field1:value1,field2:value2, //填充在單元格中的顯示內容,從this.header.fields數組中獲取屬性名field1等 // _field_id // }] // 每一行特定的樣式、屬性根據this.options.rowStyle、this.options.rowAttributes獲取 // 數組形式 // [["field","class"]] // 數組形式不能對每一行添加特定的data屬性、id以及class // // 特定的的樣式、屬性仍可由this.options.rowStyle、this.options.rowAttributes獲取 // // 以及data-index添加行號、data-uniqueId每行的唯一標識,根據options.uniqueId從data中獲取 // // tr以及checkbox中data數組的序號data-index,以便於獲取data[data-index]數據調用 this.trigger('pre-body', data); this.$body = this.$el.find('>tbody'); if (!this.$body.length) { this.$body = $('<tbody></tbody>').appendTo(this.$el); }// 頁面初始化存在tbody>tr>td的情況下,this.options.data數據由initTable獲取 //Fix #389 Bootstrap-table-flatJSON is not working // 未作分頁或后台分頁的情況返回所有數據 if (!this.options.pagination || this.options.sidePagination === 'server') { this.pageFrom = 1; this.pageTo = data.length; } for (var i = this.pageFrom - 1; i < this.pageTo; i++) { var key, item = data[i],// 行數據信息row style = {}, csses = [], data_ = '', attributes = {}, htmlAttributes = []; // 通過options.rowStyle(row,index)函數或window[options.rowStyle](row,index)獲取tbody>tr樣式 style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style); if (style && style.css) { for (key in style.css) { csses.push(key + ': ' + style.css[key]); } } // 通過options.rowAttributes(row,index)函數或window[options.rowAttributes](row,index)獲取tbody>tr屬性 attributes = calculateObjectValue(this.options, this.options.rowAttributes, [item, i], attributes); if (attributes) { for (key in attributes) { htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key]))); } } // 通過row._data,row._id,row._class,row[options.uniqueId]渲染tbody>tr if (item._data && !$.isEmptyObject(item._data)) { $.each(item._data, function (k, v) { if (k === 'index') { return; } data_ += sprintf(' data-%s="%s"', k, v); }); } html.push('<tr', sprintf(' %s', htmlAttributes.join(' ')), sprintf(' id="%s"', $.isArray(item) ? undefined : item._id), sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)), sprintf(' data-index="%s"', i), sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]), sprintf('%s', data_), '>' ); // 卡片式顯示跨列 if (this.options.cardView) { html.push(sprintf('<td colspan="%s">', this.header.fields.length)); } // 表格顯示時添加每行數據前點擊展示卡片式詳情按鈕 if (!this.options.cardView && this.options.detailView) { html.push('<td>', '<a class="detail-icon" href="javascript:">', sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen), '</a>', '</td>'); } // 遍歷this.header.fields獲取主鍵field值,再由主鍵field拼接row中的屬性取值,包括row[field] // 顯示文本row[field]調用對應的this.header.formatter[j]處理后獲取 // j即列坐標 $.each(this.header.fields, function (j, field) { var text = '', value = getItemField(item, field, that.options.escape),// 獲取row[field] type = '', cellStyle = {}, id_ = '', class_ = that.header.classes[j], data_ = '', rowspan_ = '', title_ = '', column = that.columns[getFieldIndex(that.columns, field)]; if (!column.visible) {// 篩選時設置 return; } style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; ')); // 調用that.header.formatters[j](item.field,item,i)格式化顯示內容 // 特別當單元格是復選框的時候,value返回值可以是對象形式{checked:true;disabled:true},此時無顯示文本 value = calculateObjectValue(column, that.header.formatters[j], [value, item, i], value); if (item['_' + field + '_id']) { id_ = sprintf(' id="%s"', item['_' + field + '_id']); } if (item['_' + field + '_class']) { class_ = sprintf(' class="%s"', item['_' + field + '_class']); } if (item['_' + field + '_rowspan']) { rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']); } if (item['_' + field + '_title']) { title_ = sprintf(' title="%s"', item['_' + field + '_title']); } // 調用that.header.cellStyles[j](item.field,item,i)設置單元格顯示樣式 cellStyle = calculateObjectValue(that.header, that.header.cellStyles[j], [value, item, i], cellStyle); if (cellStyle.classes) { class_ = sprintf(' class="%s"', cellStyle.classes); } if (cellStyle.css) { var csses_ = []; for (var key in cellStyle.css) { csses_.push(key + ': ' + cellStyle.css[key]); } style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; ')); } if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) { $.each(item['_' + field + '_data'], function (k, v) { if (k === 'index') { return; } data_ += sprintf(' data-%s="%s"', k, v); }); } if (column.checkbox || column.radio) { type = column.checkbox ? 'checkbox' : type; type = column.radio ? 'radio' : type; text = [sprintf(that.options.cardView ? '<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''), '<input' + sprintf(' data-index="%s"', i) + sprintf(' name="%s"', that.options.selectItemName) + sprintf(' type="%s"', type) + sprintf(' value="%s"', item[that.options.idField]) + sprintf(' checked="%s"', value === true || (value && value.checked) ? 'checked' : undefined) + sprintf(' disabled="%s"', !column.checkboxEnabled || (value && value.disabled) ? 'disabled' : undefined) + ' />', that.header.formatters[j] && typeof value === 'string' ? value : '', that.options.cardView ? '</div>' : '</td>' ].join(''); // 復選框上傳內容字段名屬性后添加true選中/false未選中值 item[that.header.stateField] = value === true || (value && value.checked); } else { value = typeof value === 'undefined' || value === null ? that.options.undefinedText : value; // getPropertyFromOther卡片式顯示時獲取標題欄的文本內容 text = that.options.cardView ? ['<div class="card-view">', that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style, getPropertyFromOther(that.columns, 'field', 'title', field)) : '', sprintf('<span class="value">%s</span>', value), '</div>' ].join('') : [sprintf('<td%s %s %s %s %s %s>', id_, class_, style, data_, rowspan_, title_), value, '</td>' ].join(''); if (that.options.cardView && that.options.smartDisplay && value === '') { // 占位符,以利於根據元素序號准確地綁定事件 text = '<div class="card-view"></div>'; } } html.push(text); }); if (this.options.cardView) { html.push('</td>'); } html.push('</tr>'); } if (!html.length) { html.push('<tr class="no-records-found">', sprintf('<td colspan="%s">%s</td>', this.$header.find('th').length, this.options.formatNoMatches()), '</tr>'); } this.$body.html(html.join('')); if (!fixedScroll) { this.scrollTo(0); } // 點擊單元格觸發單元格以及當前行點擊事件,復選框則勾選 this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) { var $td = $(this), $tr = $td.parent(), item = that.data[$tr.data('index')],// 獲取當前行的data[data-index]數據調用 index = $td[0].cellIndex,// 返回一行內單元格所在的列坐標 field = that.header.fields[that.options.detailView && !that.options.cardView ? index - 1 : index], column = that.columns[getFieldIndex(that.columns, field)], value = getItemField(item, field, that.options.escape); if ($td.find('.detail-icon').length) { return; } // 單元格點擊事件傳入單元格的field(借此獲取data中的有關數據)、顯示內容value值data[data-index][field]、 // 當前行data數據item值data[data-index]、單元格jquery對象$td that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td); // 行點擊事件傳入當前行data數據item值data[data-index]以及當前行jquery對象$tr that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr); if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) { var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName)); if ($selectItem.length) { $selectItem[0].click(); // #144: .trigger('click') bug } } }); // 展開折疊卡片式詳情 this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () { var $this = $(this), $tr = $this.parent().parent(), index = $tr.data('index'), row = data[index]; // Fix #980 Detail view, when searching, returns wrong row if ($tr.next().is('tr.detail-view')) { $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen)); $tr.next().remove(); that.trigger('collapse-row', index, row); } else { $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose)); $tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length)); var $element = $tr.next().find('td'); // options.detailFormatter執行后渲染折疊式卡片詳情文本內容,包含html標簽、Dom元素 var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], ''); if($element.length === 1) { $element.append(content); } that.trigger('expand-row', index, row, $element); } that.resetView(); }); // 綁定復選框點擊事件 this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName)); this.$selectItem.off('click').on('click', function (event) { event.stopImmediatePropagation(); var $this = $(this), checked = $this.prop('checked'), row = that.data[$this.data('index')]; if (that.options.maintainSelected && $(this).is(':radio')) { $.each(that.options.data, function (i, row) { row[that.header.stateField] = false; }); } row[that.header.stateField] = checked; if (that.options.singleSelect) { that.$selectItem.not(this).each(function () { that.data[$(this).data('index')][that.header.stateField] = false; }); that.$selectItem.filter(':checked').not(this).prop('checked', false); } that.updateSelected(); that.trigger(checked ? 'check' : 'uncheck', row, $this); }); // 由this.header.events為tbody>tr>td中子元素綁定事件 $.each(this.header.events, function (i, events) { if (!events) { return; } // fix bug, if events is defined with namespace if (typeof events === 'string') { events = calculateObjectValue(null, events); } var field = that.header.fields[i], fieldIndex = $.inArray(field, that.getVisibleFields()); if (that.options.detailView && !that.options.cardView) { fieldIndex += 1; } for (var key in events) { that.$body.find('>tr:not(.no-records-found)').each(function () { var $tr = $(this), $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex), index = key.indexOf(' '), name = key.substring(0, index), el = key.substring(index + 1), func = events[key]; $td.find(el).off(name).on(name, function (e) { var index = $tr.data('index'), row = that.data[index], value = row[field]; func.apply(this, [e, value, row, index]); }); }); } }); this.updateSelected(); this.resetView(); this.trigger('post-body'); }; // 觸發ajax事件(可以是用戶自定義的方法options.ajax),上傳數據格式為 // { // searchText:this.searchText, // sortName:this.options.sortName, // sortOrder:this.options.sortOrder, // pageSize/limit:..., // pageNumber/offset:..., // [filter]:..., // query:... // } // 觸發上傳成功調用this.load方法,觸發load-success事件、上傳失敗load-error事件 BootstrapTable.prototype.initServer = function (silent, query) { var that = this, data = {}, params = { searchText: this.searchText, sortName: this.options.sortName, sortOrder: this.options.sortOrder }, request;// ajax配置 if(this.options.pagination) { params.pageSize = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize; params.pageNumber = this.options.pageNumber; } if (!this.options.url && !this.options.ajax) { return; } // 意義??? if (this.options.queryParamsType === 'limit') { params = { search: params.searchText, sort: params.sortName, order: params.sortOrder }; if (this.options.pagination) { params.limit = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize; params.offset = this.options.pageSize === this.options.formatAllRows() ? 0 : this.options.pageSize * (this.options.pageNumber - 1); } } // this.filterColumnsPartial用於設置后台過濾??? if (!($.isEmptyObject(this.filterColumnsPartial))) { params['filter'] = JSON.stringify(this.filterColumnsPartial, null); } // 調用options.queryParams處理上傳的內容param,包括搜索文本、排序字段、排序方式 // 以及當前頁顯示幾條數據、當前頁數或limit、offset data = calculateObjectValue(this.options, this.options.queryParams, [params], data); $.extend(data, query || {}); if (data === false) { return; } if (!silent) { this.$tableLoading.show(); } request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), { type: this.options.method, url: this.options.url, data: this.options.contentType === 'application/json' && this.options.method === 'post' ? JSON.stringify(data) : data, cache: this.options.cache, contentType: this.options.contentType, dataType: this.options.dataType, success: function (res) { res = calculateObjectValue(that.options, that.options.responseHandler, [res], res); that.load(res); that.trigger('load-success', res); if (!silent) that.$tableLoading.hide(); }, error: function (res) { that.trigger('load-error', res.status, res); if (!silent) that.$tableLoading.hide(); } }); if (this.options.ajax) { calculateObjectValue(this, this.options.ajax, [request], null); } else { $.ajax(request); } }; // 初始化若設置搜索文本,開啟搜索,不支持本地數據搜索 BootstrapTable.prototype.initSearchText = function () { if (this.options.search) { if (this.options.searchText !== '') { var $search = this.$toolbar.find('.search input'); $search.val(this.options.searchText); this.onSearch({currentTarget: $search}); } } }; // getCaret改變排序點擊箭頭的上下方向 BootstrapTable.prototype.getCaret = function () { var that = this; $.each(this.$header.find('th'), function (i, th) { $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both'); }); }; // 全選以及全不選時改變全選復選框的勾選狀態,以及tr行添加或刪除selected類 BootstrapTable.prototype.updateSelected = function () { var checkAll = this.$selectItem.filter(':enabled').length && this.$selectItem.filter(':enabled').length === this.$selectItem.filter(':enabled').filter(':checked').length; this.$selectAll.add(this.$selectAll_).prop('checked', checkAll); this.$selectItem.each(function () { $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected'); }); }; // 復選框選中或撤銷選中后更新this.data數據中的[this.header.stateField]屬性,以便上傳復選框的狀態 BootstrapTable.prototype.updateRows = function () { var that = this; this.$selectItem.each(function () { that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked'); }); }; // 重置,撤銷復選框選中,以及data[i][that.header.stateField]賦值為false BootstrapTable.prototype.resetRows = function () { var that = this; $.each(this.data, function (i, row) { that.$selectAll.prop('checked', false); that.$selectItem.prop('checked', false); if (that.header.stateField) { row[that.header.stateField] = false; } }); }; // 執行this.options[BootstrapTable.EVENTS[name]]函數(類似瀏覽器默認事件),並觸發事件 BootstrapTable.prototype.trigger = function (name) { var args = Array.prototype.slice.call(arguments, 1); name += '.bs.table'; this.options[BootstrapTable.EVENTS[name]].apply(this.options, args); this.$el.trigger($.Event(name), args); this.options.onAll(name, args); this.$el.trigger($.Event('all.bs.table'), [name, args]); }; // 一定時間內觸發this.fitHeader函數調整表頭的水平偏移,垂直滾動不影響表頭 BootstrapTable.prototype.resetHeader = function () { // fix #61: the hidden table reset header bug. // fix bug: get $el.css('width') error sometime (height = 500) clearTimeout(this.timeoutId_); this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0); }; // 克隆this.$el中的表頭,置入this.$tableHeader中,出使垂直滾動時,表頭信息不變 // 調整表體水平偏移量和表體水平一致 BootstrapTable.prototype.fitHeader = function () { var that = this, fixedBody, scrollWidth, focused, focusedTemp; if (that.$el.is(':hidden')) { that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100); return; } fixedBody = this.$tableBody.get(0);// 包裹表單的.fixed-table-body元素 // .fixed-table-container有固定高度,其子元素.fixed-table-body超過該高度就顯示滾動條 scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth && fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ? getScrollBarWidth() : 0; this.$el.css('margin-top', -this.$header.outerHeight()); // 表頭聚焦的元素添加focus-temp類,從而使this.$tableHeader的同個元素獲得焦點 focused = $(':focus'); if (focused.length > 0) { var $th = focused.parents('th'); if ($th.length > 0) { var dataField = $th.attr('data-field'); if (dataField !== undefined) { var $headerTh = this.$header.find("[data-field='" + dataField + "']"); if ($headerTh.length > 0) { $headerTh.find(":input").addClass("focus-temp"); } } } } this.$header_ = this.$header.clone(true, true); this.$selectAll_ = this.$header_.find('[name="btSelectAll"]'); this.$tableHeader.css({ 'margin-right': scrollWidth }).find('table').css('width', this.$el.outerWidth()) .html('').attr('class', this.$el.attr('class')) .append(this.$header_); focusedTemp = $('.focus-temp:visible:eq(0)'); if (focusedTemp.length > 0) { focusedTemp.focus(); this.$header.find('.focus-temp').removeClass('focus-temp'); } // fix bug: $.data() is not working as expected after $.append() // that.$header_是jquery對象,如果改變了this的值,$(this).data()獲取內容和bug是咋回事??? this.$header.find('th[data-field]').each(function (i) { that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data()); }); var visibleFields = this.getVisibleFields(); // 標題欄單元格中的.fht-cell元素和表格中元素的寬度相一致,意義??? this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) { var $this = $(this), index = i; if (that.options.detailView && !that.options.cardView) { if (i === 0) { that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth()); } index = i - 1; } that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index])) .find('.fht-cell').width($this.innerWidth()); }); // 當窗口縮放時,出現滾動條,表頭表尾水平偏移情況相當 this.$tableBody.off('scroll').on('scroll', function () { that.$tableHeader.scrollLeft($(this).scrollLeft()); if (that.options.showFooter && !that.options.cardView) { that.$tableFooter.scrollLeft($(this).scrollLeft()); } }); that.trigger('post-header'); }; // 創建表尾,利用footerFormatter填充表尾內容,調用fitFooter調整表尾偏移 BootstrapTable.prototype.resetFooter = function () { var that = this, data = that.getData(), html = []; if (!this.options.showFooter || this.options.cardView) { return; } if (!this.options.cardView && this.options.detailView) { html.push('<td><div class="th-inner"> </div><div class="fht-cell"></div></td>'); } $.each(this.columns, function (i, column) { var falign = '', style = '', class_ = sprintf(' class="%s"', column['class']); if (!column.visible) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align); style = sprintf('vertical-align: %s; ', column.valign); html.push('<td', class_, sprintf(' style="%s"', falign + style), '>'); html.push('<div class="th-inner">'); html.push(calculateObjectValue(column, column.footerFormatter, [data], ' ') || ' '); html.push('</div>'); html.push('<div class="fht-cell"></div>'); html.push('</div>'); html.push('</td>'); }); this.$tableFooter.find('tr').html(html.join('')); clearTimeout(this.timeoutFooter_); this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), this.$el.is(':hidden') ? 100 : 0); }; // 調整表尾水平偏移,設置表尾fnt-cell的寬度 BootstrapTable.prototype.fitFooter = function () { var that = this, $footerTd, elWidth, scrollWidth; clearTimeout(this.timeoutFooter_); if (this.$el.is(':hidden')) { this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100); return; } elWidth = this.$el.css('width'); scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0; this.$tableFooter.css({ 'margin-right': scrollWidth }).find('table').css('width', elWidth) .attr('class', this.$el.attr('class')); $footerTd = this.$tableFooter.find('td'); this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) { var $this = $(this); $footerTd.eq(i).find('.fht-cell').width($this.innerWidth()); }); }; // toggleColumn篩選條目下拉菜單點選時更新columns[i].visible信息; // this.columns信息的改變,重新調用表頭、表體、搜索框、分頁初始化函數; // 當勾選的顯示條目小於this.options.minimumCountColumns時,勾選的條目設置disabled屬性; BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) { if (index === -1) { return; } this.columns[index].visible = checked; this.initHeader(); this.initSearch(); this.initPagination(); this.initBody(); if (this.options.showColumns) {// this.options.showColumns顯示篩選條目按鈕 var $items = this.$toolbar.find('.keep-open input').prop('disabled', false); if (needUpdate) { $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked); } if ($items.filter(':checked').length <= this.options.minimumCountColumns) { $items.filter(':checked').prop('disabled', true); } } }; // 從表體中找到data-index=index或data-uniqueid=uniqueId那一行,根據visible顯示或隱藏 BootstrapTable.prototype.toggleRow = function (index, uniqueId, visible) { if (index === -1) { return; } this.$body.find(typeof index !== 'undefined' ? sprintf('tr[data-index="%s"]', index) : sprintf('tr[data-uniqueid="%s"]', uniqueId)) [visible ? 'show' : 'hide'](); }; // 從this.column中剔除visible為false的項,返回field數組 BootstrapTable.prototype.getVisibleFields = function () { var that = this, visibleFields = []; $.each(this.header.fields, function (j, field) { // this.columns以列坐標:數據的形式保存 var column = that.columns[getFieldIndex(that.columns, field)]; if (!column.visible) { return; } visibleFields.push(field); }); return visibleFields; }; /**公共方法:通過bootstrap(fnName,argunments)調用 * * resetView(): * 調整表體的高度; * getData(): * 搜索過濾后的數據保存在this.data中,過濾前數據保存在options.data,針對數據在前台的情況; * 有過濾數據,返回過濾數據this.data,無則返回未過濾數據this.options.data; * 前台分頁,獲取this.pageFrom-1到this.pageTo的data數據或者整個data數據; * load(): * 使用后台傳回的數據或本地data數據更新data、搜索框、分頁、表體顯示; * 后台傳回數據格式為{total:,rows:,[fixedScroll]:}; * append(): * 從表格尾部插入數據; * prepend(): * 從表格頭部插入數據; * remove(): * 移除指定行數據,通過行數據row中的某個屬性比較刪除擁有相同值的行數據data; * param數據格式為{field:paramName,values:paramValues},paramName、paramValues和data對應; * removeAll(): * 移除所有行數據; * getRowByUniqueId(): * 獲取row[options.uniqueId]或者row._data[options.uniqueId]同id相等的某一行數據; * removeByUniqueId(): * 移除row[options.uniqueId]或者row._data[options.uniqueId]同id相等的某一行數據; * updateByUniqueId(): * 更新替換某一行數據,參數格式為{id:row[options.uniqueId],row:row替換數據}; * insertRow(): * 在某一行后插入數據,參數格式為{index:index行號,row:row插入數據內容}; * updateRow(): * 更新替換某一行數據,參數格式為{index:index行號,row:row替換數據}; * showRow(): * 根據{[index:index],[uniqueid:uniqueId]}找到某一行,顯示; * hideRow(): * 根據{[index:index],[uniqueid:uniqueId]}找到某一行,隱藏; * getRowsHidden(): * 獲取並返回隱藏的行,根據show將這些行數據顯示出來; * mergeCells(): * 合並單元格,傳參為{index:index.field:field,rowspan:3,colspan:4}; * 隱藏被合並單元格,重新設置顯示單元格rowspan、colspan屬性; * updateCell(): * 更新單元的顯示文本,傳參為{index:index,field:field,value:value},根據index、field找到單元格; * getOptions(): * 返回配置項; * getSelections(): * 通過過濾后的數據this.data返回選中行的數據; * getAllSelections(): * 通過未過濾的數據this.options.data返回選中行的數據; * checkAll(): * 全選; * unCheckAll(): * 全不選; * checkInvert(): * 反選; * checkAll_(): * 全選或全不選執行函數; * check(): * 選中; * unCheck(): * 取消選中; * check_(): * 選中、取消選中執行函數; * checkBy(): * 選中某幾行數據; * unCheckBy(): * 取消選中某幾行數據; * checkBy_(): * 根據條件選中、取消選中某幾行數據執行函數,obj參數格式為{field:paramName,values:paramValues}; * destory(): * 移出觸發元素,其內容、樣式通過this.$el_改為初始值,移除構造函數添加最外層包裹元素this.$container; * showLoading(): * 顯示后台數據載入文案; * hideLoading(): * 隱藏后台數據載入文案; * togglePagination(): * 分頁切換按鈕顯示隱藏分頁內容; * refresh(): * 刷新頁面到第一頁,傳入參數為{url:url,slient:slient,query:query}; * resetWidth(): * 調用fitHeader、fitFooter函數調整表頭、表尾的寬度; * showColumn(): * 根據field屬性獲得fieldIndex,再調用toggleColumn顯示某列; * hideColumn(): * 根據field屬性獲得fieldIndex,再調用toggleColumn隱藏某列; * getHiddenColumns(): * 獲得隱藏的某幾列; * filterBy(): * 設置過濾數組this.filterColumns; * options.data和this.filterColumns相符則在this.data中保留,不相符則在this.data中刪除; * 設置頁碼為1,重新調用initSearch、updatePagination渲染表格; * scrollTo(): * 設置this.$tableBody滾動條的垂直偏移,意義是移動到第幾行數據; * getScrollPosition(): * 表體滾動到頂部; * selectPage(): * 設置this.options.pageNumber當前頁,調用updatePagination更新表體,initBody或initServer方法; * prevPage(): * nextPage(): * 上一頁,下一頁; * toggleView(): * 切換卡片式顯示或者表格詳情顯示; * refreshView(): * 更新傳入的配置項options,調用destory重置,init重新渲染頁面; * resetSearch(): * 設置搜索框文本,啟動數據搜索; * expandRow_(): * 表格詳情顯示時,折疊展開按鈕執行函數; * expandRow(): * 展開對應行的卡片詳情; * collapseRow(): * 折疊對應行的卡片詳情; * expandAllRows(): * expandAllRows展開所有卡片式詳情,在表格顯示的時候; * isSubTable為真,展開父子表格的詳情; * collapseAllRows(): * expandAllRows展開所有卡片式詳情,在表格顯示的時候; * updateFormatText(): * 更新配置項中的格式化函數; */ // 調整表體的高度 BootstrapTable.prototype.resetView = function (params) { var padding = 0; if (params && params.height) { this.options.height = params.height; } this.$selectAll.prop('checked', this.$selectItem.length > 0 && this.$selectItem.length === this.$selectItem.filter(':checked').length); if (this.options.height) { var toolbarHeight = getRealHeight(this.$toolbar), paginationHeight = getRealHeight(this.$pagination), height = this.options.height - toolbarHeight - paginationHeight; this.$tableContainer.css('height', height + 'px'); } if (this.options.cardView) { this.$el.css('margin-top', '0'); this.$tableContainer.css('padding-bottom', '0'); return; } if (this.options.showHeader && this.options.height) { this.$tableHeader.show(); this.resetHeader(); padding += this.$header.outerHeight(); } else { this.$tableHeader.hide(); this.trigger('post-header'); } if (this.options.showFooter) { this.resetFooter(); if (this.options.height) { padding += this.$tableFooter.outerHeight() + 1; } } this.getCaret(); this.$tableContainer.css('padding-bottom', padding + 'px'); this.trigger('reset-view'); }; // 過濾或搜索過濾后的數據保存在this.data中,過濾前的數據保存在this.options.data,針對數據在前台的情況; // 有過濾數據,返回過濾數據this.data,無則返回未過濾數據this.options.data; // 前台分頁,獲取this.pageFrom-1到this.pageTo的data數據或者整個data數據; BootstrapTable.prototype.getData = function (useCurrentPage) { return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ? (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) : (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data); }; // 使用后台傳回的數據或本地data數據更新data、搜索框、分頁、表體顯示 // 后台傳回數據格式為{total:,rows:,[fixedScroll]:} BootstrapTable.prototype.load = function (data) { var fixedScroll = false; // #431: support pagination if (this.options.sidePagination === 'server') { this.options.totalRows = data.total; fixedScroll = data.fixedScroll; data = data[this.options.dataField]; } else if (!$.isArray(data)) { // support fixedScroll fixedScroll = data.fixedScroll; data = data.data; } this.initData(data); this.initSearch(); this.initPagination(); this.initBody(fixedScroll); }; // 從表格尾部插入數據 BootstrapTable.prototype.append = function (data) { this.initData(data, 'append'); this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; // 從表格頭部插入數據 BootstrapTable.prototype.prepend = function (data) { this.initData(data, 'prepend'); this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; // 移除指定行數據,通過行數據row中的某個屬性比較刪除擁有相同值的行數據data // param數據格式為{field:paramName,values:paramValues},paramName、paramValues和data對應 /** var ids = $.map($table.bootstrapTable('getSelections'), function (row) { return row.id; }); $table.bootstrapTable('remove', { field: 'id', values: ids }); */ BootstrapTable.prototype.remove = function (params) { var len = this.options.data.length, i, row; if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) { return; } for (i = len - 1; i >= 0; i--) { row = this.options.data[i]; if (!row.hasOwnProperty(params.field)) { continue; } if ($.inArray(row[params.field], params.values) !== -1) { this.options.data.splice(i, 1); } } if (len === this.options.data.length) { return; } this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; // 移除所有行數據 BootstrapTable.prototype.removeAll = function () { if (this.options.data.length > 0) { this.options.data.splice(0, this.options.data.length); this.initSearch(); this.initPagination(); this.initBody(true); } }; // 獲取row[options.uniqueId]或者row._data[options.uniqueId]同id相等的某一行數據 BootstrapTable.prototype.getRowByUniqueId = function (id) { var uniqueId = this.options.uniqueId, len = this.options.data.length, dataRow = null, i, row, rowUniqueId; for (i = len - 1; i >= 0; i--) { row = this.options.data[i]; if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column rowUniqueId = row[uniqueId]; } else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property rowUniqueId = row._data[uniqueId]; } else { continue; } if (typeof rowUniqueId === 'string') { id = id.toString(); } else if (typeof rowUniqueId === 'number') { if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) { id = parseInt(id); } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) { id = parseFloat(id); } } if (rowUniqueId === id) { dataRow = row; break; } } return dataRow; }; // 移除row[options.uniqueId]或者row._data[options.uniqueId]同id相等的某一行數據 BootstrapTable.prototype.removeByUniqueId = function (id) { var len = this.options.data.length, row = this.getRowByUniqueId(id); if (row) { this.options.data.splice(this.options.data.indexOf(row), 1); } if (len === this.options.data.length) { return; } this.initSearch(); this.initPagination(); this.initBody(true); }; // 更新替換某一行數據,參數格式為{id:row[options.uniqueId],row:row替換數據} BootstrapTable.prototype.updateByUniqueId = function (params) { var rowId; if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) { return; } rowId = $.inArray(this.getRowByUniqueId(params.id), this.options.data); if (rowId === -1) { return; } $.extend(this.data[rowId], params.row); this.initSort(); this.initBody(true); }; // 在某一行后插入數據,參數格式為{index:index行號,row:row插入數據內容} BootstrapTable.prototype.insertRow = function (params) { if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) { return; } this.data.splice(params.index, 0, params.row); this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; // 更新替換某一行數據,參數格式為{index:index行號,row:row替換數據} BootstrapTable.prototype.updateRow = function (params) { if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) { return; } $.extend(this.data[params.index], params.row); this.initSort(); this.initBody(true); }; // 根據{[index:index],[uniqueid:uniqueId]}找到某一行,顯示 BootstrapTable.prototype.showRow = function (params) { if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) { return; } this.toggleRow(params.index, params.uniqueId, true); }; // 根據{[index:index],[uniqueid:uniqueId]}找到某一行,隱藏 BootstrapTable.prototype.hideRow = function (params) { if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) { return; } this.toggleRow(params.index, params.uniqueId, false); }; // 獲取並返回隱藏的行,根據show將這些行數據顯示出來 BootstrapTable.prototype.getRowsHidden = function (show) { var rows = $(this.$body[0]).children().filter(':hidden'), i = 0; if (show) { for (; i < rows.length; i++) { $(rows[i]).show(); } } return rows; }; // 合並單元格,傳參為{index:index.field:field,rowspan:3,colspan:4} // 隱藏被合並單元格,重新設置顯示單元格rowspan、colspan屬性 BootstrapTable.prototype.mergeCells = function (options) { var row = options.index, col = $.inArray(options.field, this.getVisibleFields()), rowspan = options.rowspan || 1, colspan = options.colspan || 1, i, j, $tr = this.$body.find('>tr'), $td; if (this.options.detailView && !this.options.cardView) { col += 1; } $td = $tr.eq(row).find('>td').eq(col); if (row < 0 || col < 0 || row >= this.data.length) { return; } for (i = row; i < row + rowspan; i++) { for (j = col; j < col + colspan; j++) { $tr.eq(i).find('>td').eq(j).hide(); } } $td.attr('rowspan', rowspan).attr('colspan', colspan).show(); }; // 更新單元的顯示文本,傳參為{index:index,field:field,value:value},根據index、field找到單元格 BootstrapTable.prototype.updateCell = function (params) { if (!params.hasOwnProperty('index') || !params.hasOwnProperty('field') || !params.hasOwnProperty('value')) { return; } this.data[params.index][params.field] = params.value; if (params.reinit === false) { return; } this.initSort(); this.initBody(true); }; // 返回配置項 BootstrapTable.prototype.getOptions = function () { return this.options; }; // 通過過濾后的數據this.data返回選中行的數據 BootstrapTable.prototype.getSelections = function () { var that = this; return $.grep(this.data, function (row) { return row[that.header.stateField]; }); }; // 通過未過濾的數據this.options.data返回選中行的數據 BootstrapTable.prototype.getAllSelections = function () { var that = this; return $.grep(this.options.data, function (row) { return row[that.header.stateField]; }); }; // 執行全選 BootstrapTable.prototype.checkAll = function () { this.checkAll_(true); }; // 執行全不選 BootstrapTable.prototype.uncheckAll = function () { this.checkAll_(false); }; // 反選,調用updateRows執行initSort、initBody,調用updateSelect為行元素tr添加selected類 BootstrapTable.prototype.checkInvert = function () { var that = this; var rows = that.$selectItem.filter(':enabled'); var checked = rows.filter(':checked'); rows.each(function() { $(this).prop('checked', !$(this).prop('checked')); }); that.updateRows(); that.updateSelected(); that.trigger('uncheck-some', checked); checked = that.getSelections(); that.trigger('check-some', checked); }; // 全選或全不選執行函數,為什么這時又不像所在的行添加selected類??? BootstrapTable.prototype.checkAll_ = function (checked) { var rows; if (!checked) { rows = this.getSelections(); } this.$selectAll.add(this.$selectAll_).prop('checked', checked);//全選按鈕 this.$selectItem.filter(':enabled').prop('checked', checked); this.updateRows(); if (checked) { rows = this.getSelections(); } this.trigger(checked ? 'check-all' : 'uncheck-all', rows); }; // 選中 BootstrapTable.prototype.check = function (index) { this.check_(true, index); }; // 取消選中 BootstrapTable.prototype.uncheck = function (index) { this.check_(false, index); }; // 選中、取消選中執行函數 BootstrapTable.prototype.check_ = function (checked, index) { var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked); this.data[index][this.header.stateField] = checked; this.updateSelected(); this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el); }; // 選中某幾行數據 BootstrapTable.prototype.checkBy = function (obj) { this.checkBy_(true, obj); }; // 取消選中某幾行數據 BootstrapTable.prototype.uncheckBy = function (obj) { this.checkBy_(false, obj); }; // 根據條件選中、取消選中某幾行數據執行函數,obj參數格式為{field:paramName,values:paramValues} BootstrapTable.prototype.checkBy_ = function (checked, obj) { if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) { return; } var that = this, rows = []; $.each(this.options.data, function (index, row) { if (!row.hasOwnProperty(obj.field)) { return false; } if ($.inArray(row[obj.field], obj.values) !== -1) { var $el = that.$selectItem.filter(':enabled') .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked); row[that.header.stateField] = checked; rows.push(row); that.trigger(checked ? 'check' : 'uncheck', row, $el); } }); this.updateSelected(); this.trigger(checked ? 'check-some' : 'uncheck-some', rows); }; // 移出觸發元素,其內容、樣式通過this.$el_改為初始值,移除構造函數添加最外層包裹元素this.$container BootstrapTable.prototype.destroy = function () { this.$el.insertBefore(this.$container); $(this.options.toolbar).insertBefore(this.$el); this.$container.next().remove(); this.$container.remove(); this.$el.html(this.$el_.html()) .css('margin-top', '0') .attr('class', this.$el_.attr('class') || ''); // reset the class }; // 顯示后台數據載入文案 BootstrapTable.prototype.showLoading = function () { this.$tableLoading.show(); }; // 隱藏后台數據載入文案 BootstrapTable.prototype.hideLoading = function () { this.$tableLoading.hide(); }; // 分頁切換按鈕顯示隱藏分頁內容 BootstrapTable.prototype.togglePagination = function () { this.options.pagination = !this.options.pagination; var button = this.$toolbar.find('button[name="paginationSwitch"] i'); if (this.options.pagination) { button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown); } else { button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp); } this.updatePagination(); }; // 刷新頁面到第一頁,傳入參數為{url:url,slient:slient,query:query} BootstrapTable.prototype.refresh = function (params) { if (params && params.url) { this.options.url = params.url; this.options.pageNumber = 1; } this.initServer(params && params.silent, params && params.query); }; // 調用fitHeader、fitFooter函數調整表頭、表尾的寬度 BootstrapTable.prototype.resetWidth = function () { if (this.options.showHeader && this.options.height) { this.fitHeader(); } if (this.options.showFooter) { this.fitFooter(); } }; // 根據field屬性獲得fieldIndex,再調用toggleColumn顯示某列 BootstrapTable.prototype.showColumn = function (field) { this.toggleColumn(getFieldIndex(this.columns, field), true, true); }; // 根據field屬性獲得fieldIndex,再調用toggleColumn隱藏某列 BootstrapTable.prototype.hideColumn = function (field) { this.toggleColumn(getFieldIndex(this.columns, field), false, true); }; // 獲得隱藏的某幾列 BootstrapTable.prototype.getHiddenColumns = function () { return $.grep(this.columns, function (column) { return !column.visible; }); }; // 設置過濾數組this.filterColumns; // options.data和this.filterColumns相符則在this.data中保留,不相符則在this.data中刪除; // 設置頁碼為1,重新調用initSearch、updatePagination渲染表格; BootstrapTable.prototype.filterBy = function (columns) { this.filterColumns = $.isEmptyObject(columns) ? {} : columns; this.options.pageNumber = 1; this.initSearch(); this.updatePagination(); }; // 設置this.$tableBody滾動條的垂直偏移,意義是移動到第幾行數據 BootstrapTable.prototype.scrollTo = function (value) { if (typeof value === 'string') { value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0; } if (typeof value === 'number') { this.$tableBody.scrollTop(value); } if (typeof value === 'undefined') { return this.$tableBody.scrollTop();// 返回頂部 } }; // 表體滾動到頂部 BootstrapTable.prototype.getScrollPosition = function () { return this.scrollTo(); }; // 設置this.options.pageNumber當前頁,調用updatePagination更新表體,initBody或initServer方法 BootstrapTable.prototype.selectPage = function (page) { if (page > 0 && page <= this.options.totalPages) { this.options.pageNumber = page; this.updatePagination(); } }; // 前一頁 BootstrapTable.prototype.prevPage = function () { if (this.options.pageNumber > 1) { this.options.pageNumber--; this.updatePagination(); } }; // 后一頁 BootstrapTable.prototype.nextPage = function () { if (this.options.pageNumber < this.options.totalPages) { this.options.pageNumber++; this.updatePagination(); } }; // 切換卡片式顯示或者表格詳情顯示 BootstrapTable.prototype.toggleView = function () { this.options.cardView = !this.options.cardView; this.initHeader(); // Fixed remove toolbar when click cardView button. //that.initToolbar(); this.initBody(); this.trigger('toggle', this.options.cardView); }; // 更新傳入的配置項options,調用destory重置,init重新渲染頁面 BootstrapTable.prototype.refreshOptions = function (options) { //If the objects are equivalent then avoid the call of destroy / init methods // 當this.options和options長度相當,其中一個屬性不同的時候,也會被if語句提前返回??? if (compareObjects(this.options, options, true)) { return; } this.options = $.extend(this.options, options); this.trigger('refresh-options', this.options); this.destroy(); this.init(); }; // 設置搜索框文本,啟動數據搜索 BootstrapTable.prototype.resetSearch = function (text) { var $search = this.$toolbar.find('.search input'); $search.val(text || ''); this.onSearch({currentTarget: $search}); }; // 表格詳情顯示時,折疊展開按鈕執行函數 BootstrapTable.prototype.expandRow_ = function (expand, index) { var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index)); if ($tr.next().is('tr.detail-view') === (expand ? false : true)) { $tr.find('> td > .detail-icon').click(); } }; // 展開對應行的卡片詳情 BootstrapTable.prototype.expandRow = function (index) { this.expandRow_(true, index); }; // 折疊對應行的卡片詳情 BootstrapTable.prototype.collapseRow = function (index) { this.expandRow_(false, index); }; // expandAllRows展開所有卡片式詳情,在表格顯示的時候 // isSubTable為真,展開父子表格的詳情 BootstrapTable.prototype.expandAllRows = function (isSubTable) { if (isSubTable) { var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)), that = this, detailIcon = null, executeInterval = false, idInterval = -1; if (!$tr.next().is('tr.detail-view')) { $tr.find('> td > .detail-icon').click(); executeInterval = true; } else if (!$tr.next().next().is('tr.detail-view')) { $tr.next().find(".detail-icon").click(); executeInterval = true; } if (executeInterval) { try { idInterval = setInterval(function () { // 父子表格情況,從.detail-view中找到.detail-icon並點擊 detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon"); if (detailIcon.length > 0) { detailIcon.click(); } else { clearInterval(idInterval); } }, 1); } catch (ex) { clearInterval(idInterval); } } } else { var trs = this.$body.children(); for (var i = 0; i < trs.length; i++) { this.expandRow_(true, $(trs[i]).data("index")); } } }; // expandAllRows展開所有卡片式詳情,在表格顯示的時候 BootstrapTable.prototype.collapseAllRows = function (isSubTable) { if (isSubTable) { this.expandRow_(false, 0); } else { var trs = this.$body.children(); for (var i = 0; i < trs.length; i++) { this.expandRow_(false, $(trs[i]).data("index")); } } }; // 更新配置項中的格式化函數 BootstrapTable.prototype.updateFormatText = function (name, text) { if (this.options[sprintf('format%s', name)]) { if (typeof text === 'string') { this.options[sprintf('format%s', name)] = function () { return text; }; } else if (typeof text === 'function') { this.options[sprintf('format%s', name)] = text; } } this.initToolbar(); this.initPagination(); this.initBody(); }; // BOOTSTRAP TABLE PLUGIN DEFINITION // ======================= var allowedMethods = [ 'getOptions', 'getSelections', 'getAllSelections', 'getData', 'load', 'append', 'prepend', 'remove', 'removeAll', 'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId', 'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden', 'mergeCells', 'checkAll', 'uncheckAll', 'checkInvert', 'check', 'uncheck', 'checkBy', 'uncheckBy', 'refresh', 'resetView', 'resetWidth', 'destroy', 'showLoading', 'hideLoading', 'showColumn', 'hideColumn', 'getHiddenColumns', 'filterBy', 'scrollTo', 'getScrollPosition', 'selectPage', 'prevPage', 'nextPage', 'togglePagination', 'toggleView', 'refreshOptions', 'resetSearch', 'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows', 'updateFormatText' ]; $.fn.bootstrapTable = function (option) { var value, args = Array.prototype.slice.call(arguments, 1); this.each(function () { var $this = $(this), data = $this.data('bootstrap.table'), // 配置項在觸發元素的data數據中,或在js的option傳參中 options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(), typeof option === 'object' && option); if (typeof option === 'string') { if ($.inArray(option, allowedMethods) < 0) { throw new Error("Unknown method: " + option); } if (!data) { return; } value = data[option].apply(data, args); if (option === 'destroy') { $this.removeData('bootstrap.table'); } } if (!data) { $this.data('bootstrap.table', (data = new BootstrapTable(this, options))); } }); return typeof value === 'undefined' ? this : value; }; $.fn.bootstrapTable.Constructor = BootstrapTable; $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS; $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS; $.fn.bootstrapTable.locales = BootstrapTable.LOCALES; $.fn.bootstrapTable.methods = allowedMethods; $.fn.bootstrapTable.utils = { sprintf: sprintf, getFieldIndex: getFieldIndex, compareObjects: compareObjects, calculateObjectValue: calculateObjectValue }; // BOOTSTRAP TABLE INIT // ======================= $(function () { $('[data-toggle="table"]').bootstrapTable(); }); }(jQuery);