根据班级和ID </li>重新订购<li>

时间:2015-01-06 16:20:01

标签: jquery

我有许多按钮(动态生成)和一些列表项,按下面的颜色分组。

我有一些代码,当您单击标签按钮时,它会将相关颜色带到列表顶部。但是,它不保持数字顺序。因此,例如,当点击“标签”时,我总是希望ID为“blue_1”的列表项显示在列表的顶部。

帮助!多年来我一直对此感到难过。

$('label').on('click', function(){
  
  // re-order colours in numerical order
}
<ul>
  <li class="blue" id="blue_1">Blue</li>
  <li class="blue" id="blue_2">Blue</li>  
  <li class="blue" id="blue_3">Blue</li>  
  <li class="blue" id="blue_4">Blue</li>  
  <li class="blue" id="blue_5">Blue</li>  
  <li class="blue" id="blue_6">Blue</li>  
  <li class="red" id="red_1">Red</li> 
  <li class="red" id="red_2">Red</li> 
  <li class="red" id="red_3">Red</li> 
  <li class="red" id="red_4">Red</li> 
  <li class="red" id="red_5">Red</li> 
  <li class="red" id="red_6">Red</li> 
</ul>

<--! these are dynamically generated -->

  <label id="red">Red button</label>
  <label id="blue">Blue button</label>

所以我想要实现的目标:

点击红色按钮,此列表命令为:

     <ul>
      <li class="red" id="red_1">Red</li>  <!-- always top of the group and in this order-->
      <li class="red" id="red_2">Red</li> 
      <li class="red" id="red_3">Red</li> 
      <li class="red" id="red_4">Red</li> 
      <li class="red" id="red_5">Red</li> 
      <li class="red" id="red_6">Red</li> 
      <li class="blue" id="blue_1">Blue</li> <!-- always top of the group and in this order -->
      <li class="blue" id="blue_2">Blue</li>  
      <li class="blue" id="blue_3">Blue</li>  
      <li class="blue" id="blue_4">Blue</li>  
      <li class="blue" id="blue_5">Blue</li>  
      <li class="blue" id="blue_6">Blue</li>  
    </ul>

蓝色反之亦然。我总是希望带有1的ID出现在颜色组的顶部,因此前置不起作用。

2 个答案:

答案 0 :(得分:0)

您可以将data-position属性添加到每个列表项,然后使用以下jQuery重新排序。

 <ul class="listitems">
     <li data-position="3">Item 3</li>
     <li data-position="2">Item 2</li>
     <li data-position="1">Item 1</li>
     <li data-position="4">Item 4</li>
 </ul>

$(".listitems li").sort(sort_li).appendTo('.listitems');
  function sort_li(a, b){
  return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;    
}

答案 1 :(得分:0)

$('label').on('click', function () {
    $('.' + this.id).prependTo('ul');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
    <li class="blue" id="blue_1">Blue1</li>
    <li class="blue" id="blue_2">Blue2</li>
    <li class="blue" id="blue_3">Blue3</li>
    <li class="blue" id="blue_4">Blue4</li>
    <li class="blue" id="blue_5">Blue5</li>
    <li class="blue" id="blue_6">Blue6</li>
    <li class="red" id="red_1">Red1</li>
    <li class="red" id="red_2">Red2</li>
    <li class="red" id="red_3">Red3</li>
    <li class="red" id="red_4">Red4</li>
    <li class="red" id="red_5">Red5</li>
    <li class="red" id="red_6">Red6</li>
</ul>
<label id="red">Red button</label>
<label id="blue">Blue button</label>