jQuery reorder list items based on class

社会主义新天地 提交于 2019-12-19 19:54:06

问题


Is there a simple way to reorder my list items using a class?

I want to specify a class to feature those items at the top of the list first, with other list items listed below.

<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>

Desired output:

<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>

Thanks!


回答1:


You can prepend the .featured elements to their containing ul to move them to the top of the list. Try this:

$('.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>



回答2:


To add to @Rory McCrossan's answer, I've added the ability to sort it with navigation buttons

$("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



来源:https://stackoverflow.com/questions/25804721/jquery-reorder-list-items-based-on-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!