jQuery根据类重新排序列表项

时间:2014-09-12 09:12:27

标签: jquery list html-lists

有没有一种简单的方法可以使用类重新排序列表项?

我想指定一个类来首先在列表顶部显示这些项目,下面列出了其他列表项。

<ul class="order-me">
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="featured">featured content</li>
    <li class="">normal content</li>
    <li class="featured">featured content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
</ul>

期望的输出:

<ul class="order-me">
    <li class="featured">featured content</li>
    <li class="featured">featured content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
</ul>

谢谢!

2 个答案:

答案 0 :(得分:10)

您可以将.featured元素添加到其包含ul的元素中,以将它们移动到列表顶部。试试这个:

$('.featured').prependTo('.order-me');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="order-me">
  <li class="">normal content</li>
  <li class="">normal content</li>
  <li class="featured">featured content</li>
  <li class="">normal content</li>
  <li class="featured">featured content</li>
  <li class="">normal content</li>
  <li class="">normal content</li>
</ul>

答案 1 :(得分:1)

要添加@Rory McCrossan的答案,我已经添加了使用导航按钮对其进行排序的功能

$("ul.order-nav li").click(function() {
  // Find the Data attribute from unordered list [.order-nav]
  var sortClass = '.' + $(this).data('sort-by');
  // Prepent the [li] with matching class to top of [ul]
  $(sortClass).prependTo('.order-me');
});

Here is the Fiddle