项目中有要用到对表格进行排序的操作,比如现价,涨幅等等,之前的想法很简单,点一下表头,然后清空,再对这些数据进行重新排序,最后再渲染一遍,非常麻烦。后来转念一想,DOM节点也是对象啊,似乎可以也可以排序,试了一下,bingo!
感悟 : 改变思维,快速排序
// @charset "utf-8";
/**
* 表格排序(练习)
* @author 应杲臻(yinggaozhen@myhexin.com)
* @create 2015-11-12 09:34
*/
(function($, window) {
var ext = 'gSort';
var bodyItemSuffix = 'bdData';
var defaultOptions = {
sortHeadDom : '',
sortBodyDom : '',
sortHeadTag : 'g_sort_tag',
sortBodyItem : 'tr',
onLoadSort : 'desc',
defaultClassSortMap : {
'up' : 'asc',
'down' : 'desc'
}
}
function isExsitDom(o) {
return $(o).length > 0 ? true : false;
}
var gSort = function(options) {
var me = this,
options = $.extend({}, defaultOptions, options);
if (!isExsitDom(options.sortBodyDom) || !isExsitDom(options.sortHeadDom)) return;
me.options = options;
return me;
};
gSort.prototype = {
init : function() {
var me = this;
me.$hEl = $(me.options.sortHeadDom);
me.$bEl = $(me.options.sortBodyDom);
me.recordBodyItems();
me.bindHeadTagClickEvt();
return me;
},
recordBodyItems : function() {
var me = this;
if (typeof me.$bEl.data(bodyItemSuffix) == 'undefined') {
var $bodyItems = me.$bEl.find(me.options.sortBodyItem);
if (!isExsitDom($bodyItems)) return;
me.$bEl.data(bodyItemSuffix, $bodyItems);
}
return me;
},
bindHeadTagClickEvt : function () {
var me = this,
headTag = me.options.sortHeadTag || '';
var $tagHeads = me.$hEl.find('[' + headTag + ']');
if (!isExsitDom($tagHeads)) return;
$tagHeads.unbind().bind('click', function() {
var $choseHead = $(this),
tagIndex = $choseHead.parent().index();
me.gSort(tagIndex, me.opearteHeadStatus($choseHead, 'change'));
})
},
opearteHeadStatus : function(o, opearte) {
var me = this,
opearte = opearte || 'get';
if (opearte == 'change') {
var status = me.opearteHeadStatus(o);
status == 'down' ? o.find('i').attr('class', 'up') : o.find('i').attr('class', 'down');
return status;
}
return o.find('i').attr('class') || '';
},
gSort : function(index, sortRule) {
var me = this,
sortRule = me.options.defaultClassSortMap[sortRule] || 'asc',
$reDta = me.$bEl.data(bodyItemSuffix);
var sortSymbol = sortRule == 'asc' ? 1 : -1;
$reDta.sort(function(a, b) {
var cpreA = me.getCpreDta(a, index),
cpreB = me.getCpreDta(b, index);
if (cpreA > cpreB) return 1 * sortSymbol;
if (cpreA < cpreB) return -1 * sortSymbol;
return 0;
});
me.$bEl.html($reDta);
},
getCpreDta : function(o, index) {
return parseFloat($(o).find('td').eq(index).text());
}
}
return window[ext] = gSort;
})($, window);