如何使用javascript按编号类对div进行排序?

时间:2016-03-11 12:47:51

标签: javascript jquery

<pre>
    <div>
      <div class="abc grid-row">
        <div class="grid-cell position_2">
            <img src="#">
        </div>
        <div class="grid-cell position_1">
            <img src="#">
        </div>
      </div>
      <div class="abc grid-row">
        <div class="grid-cell position_2">
            <img src="#">
        </div>
        <div class="grid-cell position_3">
            <img src="#">
        </div>
        <div class="grid-cell position_1">
            <img src="#">
        </div>
      </div>
      <div class="def grid-row">
        <div class="grid-cell position_2">
            <img src="#">
        </div>
        <div class="grid-cell position_1">
            <img src="#">
        </div>
      </div>
    </div>
</pre>

我想迭代每个网格行,按位置类按数字顺序对子div进行排序。因此position_1将始终是每个网格行中的第一个子div。

当我尝试使用jQuery时,子div被分类到其他行,我需要阻止。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

sort

中的grid-cell上使用grid-row

$('.grid-row').each(function() {
  var cells = $('.grid-cell', this).sort(function(a, b) {
    return parseInt(a.className.match(/[0-9]+/)[0]) > parseInt(b.className.match(/[0-9]+/)[0]);
  });
  $(this).html(cells);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <div class="abc grid-row">
    <div class="grid-cell position_2">
      2
    </div>
    <div class="grid-cell position_1">
      1
    </div>
  </div>
  <div class="abc grid-row">
    <div class="grid-cell position_2">
      2
    </div>
    <div class="grid-cell position_3">
      3
    </div>
    <div class="grid-cell position_1">
      1
    </div>
  </div>
  <div class="def grid-row">
    <div class="grid-cell position_2">
      2
    </div>
    <div class="grid-cell position_1">
      1
    </div>
  </div>
</div>

答案 1 :(得分:0)

我知道你问过一个javascript解决方案,但你也可以考虑看一下Flexbox。你可以这样做:

.abc {
  display:flex;
  flex-direction:column;
  }
<div class="abc grid-row">
    <div class="grid-cell position_2" style="order:2">
      2
    </div>
    <div class="grid-cell position_3" style="order:3">
      3
    </div>
    <div class="grid-cell position_1" style="order:1">
      1
    </div>
  </div>

答案 2 :(得分:0)

$('.grid-row').each(function(){
    var $row = $(this), $cells = $();  //create an empty list
    for(var i=0; i<5; ++i){
        //append the items for each "position" to the list
        $.merge($cells, $row.find("> .grid-cell.position_"+i));
    }
    //append the cells in the right order to the row
    $row.append($cells);
})

//a utility to fetch the position
function getPosition(node){
    var m = node.className.match(/\bposition_(\d+)\b/);
    return +(m && m[1] || -Infinity);
}

$('.grid-row').each(function(){
    var $row = $(this);
    $row.find('> .grid-cell').sort(function(a, b){
        return getPosition(a) - getPosition(b);
    }).appendTo($row);
});