按班级将div分为三类?

时间:2016-03-10 22:36:17

标签: jquery sorting

我有一组div需要分为三类。他们目前看起来像这样 -

<div class="offline"></div>
<div class="online"></div>
<div class="offline"></div>
<div class="offline"></div>
<div class="deleted"></div>
<div class="online"></div>
<div class="offline"></div>

我需要它看起来像这样 -

<div class="online"></div>
<div class="online"></div>
<div class="offline"></div>
<div class="offline"></div>
<div class="offline"></div>
<div class="offline"></div>
<div class="deleted"></div>

我看到了一些使用sort()和append()分类为两个部分的解决方案,但我找不到三个部分的任何内容。

2 个答案:

答案 0 :(得分:1)

试试这个:

var set = [];
$('div').each(function() {
  var that = $(this);
  var cl = that.attr('class');
  if ($.inArray(cl, set) == -1) {
    set.push(cl);
  }
});
set.sort();

var div_0 = $('.' + set[0]).clone();
var div_1 = $('.' + set[1]).clone();
var div_2 = $('.' + set[2]).clone();
$('body').html('').append(div_2).append(div_1).append(div_0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="offline">offline</div>
<div class="online">online</div>
<div class="offline">offline</div>
<div class="offline">offline</div>
<div class="deleted">deleted</div>
<div class="online">online</div>
<div class="offline">offline</div>

答案 1 :(得分:1)

这里有一个关于如何使用jQuery和两个简单​​for循环来解决这个问题的小例子。 jsfiddle

&#13;
&#13;
var scope = $('#scope');
var containers = $('div', scope);
var order = [
  'online',
  'offline',
  'deleted'
];

$(document).ready(function(){
    //clear current scope and append in loop
    scope.html('');
    for (i = 0; i < order.length; i++) { 
        for (j = 0; j < containers.length; j++) {
    	    if (containers.eq(j).hasClass(order[i])) {
      	        scope.append(containers.eq(j));
            }
       }
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scope">
  <div class="offline">offline</div>
  <div class="online">online</div>
  <div class="offline">offline</div>
  <div class="offline">offline</div>
  <div class="deleted">deleted</div>
  <div class="online">online</div>
  <div class="offline">offline</div>
</div>
&#13;
&#13;
&#13;