jQuery 排序元素
示例
为了高效地对元素进行排序(一次并以最小的DOM中断),我们需要:
找到元素
根据设定条件排序
重新插入DOM
<ul id='my-color-list'>
<li class="disabled">Red</li>
<li>Green</li>
<li class="disabled">Purple</li>
<li>Orange</li>
</ul>找到他们-或.children().find()
这将给我们带来一个类似数组的对象。
var$myColorList=$('#my-color-list');
//一层较深的元素将获取.children(),任何较深的元素将与.find()集成
var$colors=$myColorList.children('li');
重新安排-Array.prototype.sort()
当前已将其设置为根据HTML内容(即其颜色)以升序返回元素。
/**
*Bind$colorstothesortmethodsowedon'thavetotravelup
*allthesepropertiesmorethanonce.
*/
varsortList=Array.prototype.sort.bind($colors);
sortList(function(a,b){
//缓存第一个元素(a)和下一个兄弟元素(b)的内部内容
varaText=a.innerHTML;
varbText=b.innerHTML;
//返回-1会将元素`a`放置在元素`b`之前
if(aText<bText){
return-1;
}
//返回1则相反
if(aText>bText){
return1;
}
//返回0会使它们保持原样
return0;
});
插入它们-.append()
请注意,我们不需要先分离元素-append()将移动DOM中已经存在的元素,因此我们不会有多余的副本
//把它放回我们得到它的地方
$myColorList.append($colors);
变得可爱
添加排序按钮
<!-- previous HTML above -->
<button type='button' id='btn-sort'>
Sort
</button>设置排序方向的初始值
var ascending = true;
缓存我们的DOM元素,并sortList()在此处最小化我们的DOM处理
var $myColorList = $('#my-color-list');
var $colors = $myColorList.children('li');
var sortList = Array.prototype.sort.bind($colors);将所有内容包装到doSort()函数中
//将sortList()并分离/追加调用到这个可移植的小东西中
var doSort = function ( ascending ) {
sortList(function ( a, b ) {
//...
});
$myColorList.append($colors);
};为添加点击处理程序$('#btn-sort')
$('#btn-sort').on('click', function () {
//运行排序并传递方向值
doSort(ascending);
//切换方向并保存
ascending = !ascending;
});现在都在一起了
var ascending = true;
var $myColorList = $('#my-color-list');
var $colors = $myColorList.children('li');
var sortList = Array.prototype.sort.bind($colors);
var doSort = function ( ascending ) {
sortList(function ( a, b ) {
var aText = a.innerHTML;
var bText = b.innerHTML;
if ( aText < bText ) {
return ascending ? -1 : 1;
}
if ( aText > bText ) {
return ascending ? 1 : -1;
}
return 0;
});
$myColorList.append($colors);
};
$('#btn-sort').on('click', function () {
doSort(ascending);
ascending = !ascending;
});奖金
多级排序(对排序后的元素进行分组)
//...
var doSort = function ( ascending ) {
sortList(function ( a, b ) {
//...initial sorting...
}).sort(function ( a, b ) {
//我们将退回的物品重新分类
var aClass = a.className;
var bClass = b.className;
//让我们将禁用项归为一组,并放在最后
/**
* If the two elements being compared have the same class
* then there's no need to move anything.
*/
if ( aClass !== bClass ) {
return aClass === 'disabled' ? 1 : -1;
}
return 0;
});
//并通过重新插入来完成
$myColorList.append($colors);
};
//...您可以再走一步吗?
添加另一个按钮以切换禁用的组排序
MDN-阵列。prototype.sort()