Jquery基于属性值排序div(降序)

时间:2017-10-23 11:46:07

标签: javascript jquery html

我有一个ajax函数,它实际上每隔3分钟从服务器中提取这个message_count数据并相应地更新每个播放器的属性...现在我想让这个基于message_count属性值的ajax调用后div自动排序降序...所以获得更多消息的玩家将成为第一个div。

var sortedDivs = jQuery(".players").find(".player").toArray().reverse(sorter);
jQuery.each(sortedDivs, function(index, value) {
  jQuery(".players").append(value);
});

function sorter(a, b) {
  return a.getAttribute('message_count') - b.getAttribute('message_count');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="players">
  <div class="player" message_count="8">8</div>
  <div class="player" message_count="2">2</div>
  <div class="player" message_count="0">0</div>
  <div class="player" message_count="1">1</div>
</div>

3 个答案:

答案 0 :(得分:2)

使用jquery .sort可以轻松完成

&#13;
&#13;
var players = $(".players div");
var temp = players.sort(function(a,b){
  return parseInt($(b).attr("message_count")) - parseInt($(a).attr("message_count"));
});
$(".players").html(temp);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="players">
  <div class="player" message_count="8">Div 8</div>
  <div class="player" message_count="2">Div 2</div>
  <div class="player" message_count="0">Div 0</div>
  <div class="player" message_count="1">Div 1</div>
 </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

   $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).attr('message_count'));
      var contentB =parseInt( $(b).attr('message_count'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   })

答案 2 :(得分:0)

您可以使用javascript sort()方法,只需反转查询。

.sort(function(a, b){return b.getAttribute('message_count') - a.getAttribute('message_count'))

&#13;
&#13;
var sortedDivs = jQuery(".players").find(".player").toArray().sort(function(a, b){return parseInt(b.getAttribute('message_count')) - parseInt(a.getAttribute('message_count'))});

jQuery.each(sortedDivs, function(index, value) {
  jQuery(".players").append(value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="players">
  <div class="player" message_count="8">8</div>
  <div class="player" message_count="2">2</div>
  <div class="player" message_count="0">0</div>
  <div class="player" message_count="1">1</div>
</div>
&#13;
&#13;
&#13;