jQuery在类名上排序列表项

我有一个列表,我需要根据类名进行排序。

活动的应该在顶部,没有类的应该在中间,而sm类应该在底部。

此列表也应该依赖于alfabetical顺序。

得到这个结果最好的是什么?

 

您似乎并不需要移动.sm元素 – 如果您选择正确的方法来修改列表,它们将始终保持在同一位置:

 $('.options').prepend(function() { var elements = [].slice.call(this.querySelectorAll('li:not(.sm)'), 0); elements.sort(function(a, b) { return (a.className.indexOf('active') === -1) - (b.className.indexOf('active') === -1) || a.querySelector('input').value.localeCompare(b.querySelector('input').value) }); return elements; }); 

演示 。 请注意, prepend()方法会移动DOM中的元素(而不是重新创建其副本)。

 $('.options').each(function () { $('.active', this).prependTo(this); $('.sm', this).appendTo(this); }); 

我不确定你是如何处理.sm项目的,但这会完成大部分的排序。

 var $options = $('.options'), items = $options.find('li').get(); items.sort(function(first, second) { var $first = $(first), $second = $(second); if ($first.hasClass('active') && !$second.hasClass('active')) { // Filter .active above everything return -1; } else if($first.hasClass('sm') && !$second.hasClass('sm')) { // Filter sm below everything return 1; } // At this point we know that they have the same class so compare the text return $first.find('label').text() < $second.find('label').text() ? -1 : 1; }); // Reorder the dom $options.html(items);