Home  >  Article  >  Web Front-end  >  Share a self-written table sorting js plug-in (efficient and concise)_javascript skills

Share a self-written table sorting js plug-in (efficient and concise)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:00:151084browse

For example: jQuery's table sorting plug-in (I didn't use it because I felt it was too troublesome to use or I didn't know its specific usage), the original js table sorting plug-in, etc. Finally, I compared it - I used an original js table sorting plug-in. plug-in, and made some modifications based on it. Although it was a bit reluctant or uncomfortable to use in some places, it finally achieved the functions needed at the time. Two days ago, I made some modifications to the original table - adding the function of changing colors between rows, and the problem appeared - the effect was confusing; after inspection and analysis, the problem lies in the table sorting plug-in code - the other The original code is difficult to understand. To modify it, it is better to write a new table sorting plug-in.

Write as you like. Table sorting is actually very simple: just take out the values ​​of all sorting columns and store them in an array (and the row objects corresponding to each column are also stored in an array), and then sort the values ​​of the columns. Sort an array (and sort an array of row objects). The table sorting plug-in code is posted below:

Copy the code The code is as follows:

/**
* @description 테이블 정렬 구현
* @author 블로그:http://www.cnblogs.com/know/
* @date 2011-10-28
**/
(function () {
//초기화 구성 개체
var _initConfig = null;
var _tableObj = null, _tbodyObj = null, _tBodyIndex = 0;
//각 현재 정렬 모드에서 (정렬된) 행 배열을 저장하는 개체 - 이 변수는 IsLazyMode=true
var _trJqObjArray_Obj = null
/**
*/ Function_GetOnValueArray (Trjqobjarr, TDIndex, TD_VALATTR, TD_DATTYPE) {
VAR TDORDERVALR = 새 배열 () dval; _tbodyObj.find ("TR" ).each(function (i, trItem)
trObj = $(trItem);
trJqObjArr.push(trObj);
tdObj = trObj.find("td")[tdIndex]
tdObj); tdVal = td_valAttr ? tdObj.attr(td_valAttr) : tdObj.text();
tdVal = _GetValue(tdVal, td_dataType)
tdOrderValArr.push(tdVal)}); OrderValArr ;
}
/**
* 정렬 방식 추가 방법(rule)
* @private
* @param trJqObjArr: (외부 입력) 정렬된 행을 저장할 배열, tdIndex: 정렬 열 인덱스, td_valAttr: 정렬 열 가져오기 Value 속성, td_dataType: 정렬 열의 값 유형
**/
function _GetJqObjById(id) {
return "string" == typeof (id) ? $("#" id) );
};
/**
* jQuery 객체를 반환하는 메서드
* @private
**/
function _Sort(tdIndex, options) {
var trJqObjArr = null; !_trJqObjArray_Obj && (_trJqObjArray_Obj = {});
trJqObjArr = _trJqObjArray_Obj[tdIndex];
}
var isExist_trJqObjArr = true
if (!trJqObjArr) {
isExist_trJqObjArr = 거짓 trJqObjArr = new Array();
var tdOrderValArr = _GetOrderTdValueArray(trJqObjArr, tdIndex, options.ValAttr, options.DataType);
var sort_len = tdOrderValArr.length - 1; = options.Desc ? ">" : "<"
for (var i = 0; i < sort_len; i ) {
isExchanged = false
for (var j = sort_len; j > i; j--) {
if (eval(tdOrderValArr[j] CompareOper tdOrderValArr[j - 1])) {
_ExchangeArray(tdOrderValArr, j ); 배열의 행 객체
_ExchangeArray(trJqObjArr, j);
isExchanged = true;
}
}
//1회 비교 후가 아니면 교환 시 루프를 종료합니다.
if ( !isExchanged)
break
}
_initConfig.IsLazyMode && (_trJqObjArray_Obj[tdIndex] = trJqObjArr)
}
if (trJqObjArr) {
if (options.Toggle) {
_initConfig.IsLazyMode && isExist_trJqObjArr && trJqObjArr.reverse();
options.Desc = !options.Desc;
}
_ShowTable(trJqObjArr); /**
* 정렬 방법
* @private
* @param tdIndex: 정렬 열의 인덱스, 옵션: 정렬 열의 규칙 구성 개체
**/
function _ShowTable(trJqObjArr) {
_tbodyObj.html("")
for (var n = 0, len = trJqObjArr.length; n < len; n ) {
_tbodyObj.append(trJqObjArr[n]);
$.isFunction(_initConfig.OnShow) && (_initConfig.OnShow(n, trJqObjArr[n], _tbodyObj ))
}
}
/**
* 정렬된 테이블 표시
* @private
* @param trJqObjArr: tr 객체의 정렬된 배열
**/
function _ExchangeArray(array, j) {
var temp = array[j]
array[j ] = array[j - 1]
array[j - 1] = temp;
}
/**
* 배열의 항목을 교환하는 방법
* @private
* @param array: array, j: 교환 배열 항목의 tail 항목 인덱스
**/
function _GetValue(tdVal, td_dataType) {
스위치(td_dataType) {
case " int":
return parsInt(tdVal) || 0;
case "float":
return parsFloat(tdVal) || 0;
case " date":
return Date.parse (tdVal) || 0;
case "string":
기본값:
return tdVal.toString() || ""
}
/**
* 정렬 방식 추가 방법(rule)
* @private
* @param tdVal : 정렬 컬럼의 값, td_dataType : 정렬 컬럼의 값 타입
**/
function _SetOrder(obj, index, options) {
var orderSettings = {
ValAttr: false, //정렬 열의 Value 속성, 기본값 For: innerText
DataType: "string" , //정렬 열의 값 유형(사용 가능한 값: int|float|date|string)
OnClick: null, //정렬(클릭) 시 트리거되는 메서드
Desc: true, //(여부 내림차순) 정렬 방법, 기본값은 내림차순
Toggle: true, //정렬 방법 전환
DefaultOrder: false //기본 정렬 방법인지 여부
}
$ ; .extend(orderSettings, options);
orderSettings.DataType = orderSettings.DataType.toLowerCase();
obj = _GetJqObjById(obj);
//정렬을 트리거하는 이벤트 바인딩
obj.bind ("클릭", 함수 () {
_Sort(index, orderSettings);
$.isFunction(orderSettings.OnClick) && orderSettings.OnClick();
}); _Sort(색인, 순서설정)
}
var _api = {
Init: function (obj, tBodyIndex, options) {
if (obj == null || typeof (obj) == undefined) {
alert("TableOrder initialization parameters Empty or incorrect! ");
return;
}
_tableObj = _GetJqObjById(obj);
_tBodyIndex = tBodyIndex || 0;
_tbodyObj = _tableObj.find("tbody: eq(" _tBodyIndex ")");
options = options || {};
_initConfig = {
IsLazyMode: true, //Whether it is lazy mode, the default is: true
OnShow: null //Method for displaying the table after sorting, params: trIndex, trJqObj, tbodyObj
};
$.extend(_initConfig, options);
_trJqObjArray_Obj = null;
},
SetOrder : function (obj, index, options) {
if (_tableObj == null) {
alert("_tableObj has not been initialized yet!");
return;
}
_SetOrder(obj, index, options);
}
};
window.TableOrderOper = _api;
})();

It is used as follows:
Copy code The code is as follows:






< ;td width="50" align="center">size
< /tr>









< ;td align="center" _order="2008/3/6 20:12:23">2008/3/6 20:12:23
















Name / Type upload time
JSCSS 2008/9/12 8:51:09 433247
AJAX 11394
EXT 2008/10/4 20:21:54 351
Index 2008/10/4 20:24:11 14074< ;/td>
ORDER 2008/10/4 20:24:11 2844





I have tried my best to write the comments in the code as clearly as possible. What needs to be added is:

1.js uses closures. I emphasize that the code should be as concise and easy to understand as possible.

2. IsLazyMode attribute setting, IsLazyMode=true, is applicable to the current table to be sorted, which is unchanged, that is, there will be no ajax operation of adding, deleting and changing rows, and you can see this after looking at the code Benefits: Traverse the corresponding row objects of the column to be sorted only once, and save the sorted row object array in the global object. The next time you sort, directly retrieve the corresponding row object array through tdIndex (the index of the sort column), and Reversing the array can achieve the sorting effect, which can improve code execution efficiency (performance) to a certain extent; IsLazyMode=false, which is suitable for situations where the table currently to be sorted will change, such as ajax operations such as adding, deleting, and changing rows. .

3. Consider that the amount of table data to be sorted is generally not large, and the array sorting uses the bubble sort algorithm.

4.OnShow: null //Method for displaying the sorted table, params: trIndex, trJqObj, tbodyObj - can be conveniently used to set the line wrapping style of the sorted table, etc., and also for performance optimization considerations.

Okay, finally, I attach the plug-in js and demo. The current implementation can only be said to meet the needs of my current project very well or is suitable for most scenarios. If so, have you considered it? or something bad, I hope that friends who pass by can feel free to leave comments so that everyone can communicate and learn from each other!

OrderTable.rar

Original address: cnblogs know
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn