按元素的值排序列表

时间:2015-07-07 12:51:40

标签: javascript jquery

我正在尝试按每个列表项的子元素排序列表。我有一个分数,并希望按分数排序。

jsFiddle

var ordering = 'asc';

    function orderList(listID) {
        var container = document.getElementById(listID);
        var contents = container.querySelectorAll("li");

        var list = [];
        for(var i=0; i<contents.length; i++){
            list.push(contents[i]);
        }

        list.sort(function(a, b){
            var aa = parseInt(a.innerHTML);
            var bb = parseInt(b.innerHTML);
            return aa < bb ? -1 : (aa > bb ? 1 : 0);
        });

        if (ordering === 'asc') {
            list.reverse();
            ordering = 'desc';
        } else {
            ordering = 'asc';
        }

        for(var i=0; i<list.length; i++){
            container.insertBefore(list[i], container.firstChild);
        }

    }

    $('body').on('click', '.order', function(){
        orderList('list');
    });

想要使用任何插件,只需JavaScript或jQuery。

4 个答案:

答案 0 :(得分:0)

您只需要更改排序功能,以便它使用<strong class="score">中的分数:

    list.sort(function(a, b){
        var aVal = parseInt($(a).find(".score").text(), 10);
        var bVal = parseInt($(b).find(".score").text(), 10);
        return aVal - bVal;
    });

如果你使用jquery,js的整个部分可以简化为:

var ordering = 'asc';

function orderList(listID) {
    // Get container
    var $container = $("#" + listID);
    // Get elements and detach from container.
    var $contents = $container.find("li").detach();

    // Decide order.
    ordering = (ordering === 'asc') ? 'desc' : 'asc';
    var sortOrder = (ordering === 'asc') ? 1 : -1;

    // Sort
    $contents.sort(function(a, b){
        var aVal = parseInt($(a).find(".score").text(), 10);
        var bVal = parseInt($(b).find(".score").text(), 10);
        return (aVal - bVal) * sortOrder;
    });

   // Change the text of sort div
    var display = ordering.slice(0, 1).toUpperCase() + ordering.slice(1);
    $('.order i').text(display); 
    $container.append($contents);
}

$('body').on('click', '.order', function(){
    orderList('list');
});

jsFiddle

答案 1 :(得分:0)

由于您使用的是jQuery,因此可以简化为

&#13;
&#13;
var ordering = 1;

function orderList(listID) {
  var container = $('#' + listID);

  container.children().sort(function(a, b) {
    var aa = parseInt($(a).find('.score').text(), 10);
    var bb = parseInt($(b).find('.score').text(), 10);
    return (aa - bb) * ordering;
  }).appendTo(container);

  ordering *= -1;
}

$('body').on('click', '.order', function() {
  orderList('list');
});
&#13;
ul,
li {
  display: inline-block;
}
li {
  background-color: #eaeaea;
  position: relative;
  float: left;
  margin-bottom: 5px;
}
.score {
  position: absolute;
  top: 30px;
  left: 20px;
  font-size: 50px;
}
.content {
  position: relative;
  float: left;
  padding-left: 50px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="order">Order <i>Asc</i></span>

<ul id="list" class="list">
  <li class="list-item">
    <strong class="score">5</strong>
    <blockquote class="content">
      Pellentesque ligula nibh, lacinia eget pharetra ut, vulputate vitae odio. Donec non mattis nisi. Pellentesque elit leo, tincidunt nec felis vitae, aliquet imperdiet purus. In elit ante, vestibulum non accumsan at, volutpat eget dolor. Quisque ut tincidunt
      elit. Curabitur rutrum dignissim enim ac aliquet. Curabitur et aliquam nisl.
      <cite>Malcolm Reynolds</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">8</strong>
    <blockquote class="content">
      Duis ac nisi id lorem rhoncus tempus eu sit amet nisi. Aenean ultrices congue ligula, ac molestie velit ultricies a. Nulla ac nunc et nisi placerat interdum sit amet ut erat. Integer vulputate nulla id orci cursus, eget ullamcorper justo ultricies. Nulla
      lorem dui, euismod non porttitor eu, sagittis in lacus. In suscipit lectus non viverra luctus. Pellentesque egestas, dolor at luctus eleifend, velit dui viverra risus, ac rutrum sapien ante at massa. Donec imperdiet consequat laoreet.
      <cite>Zoe Washburne</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">3</strong>
    <blockquote class="content">
      Etiam posuere, magna sit amet ullamcorper auctor, odio urna tempor velit, sit amet tincidunt lorem diam a velit. Integer a dapibus nunc. In iaculis vel sem ut gravida.
      <cite>Hoban Washburne</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">10</strong>
    <blockquote class="content">
      Etiam condimentum sodales dui in vestibulum. Vivamus euismod egestas porttitor. Proin dictum tempor euismod. Suspendisse elit nulla, elementum eu ornare in, tempus in massa. Proin elit sem, posuere nec tempor eget, suscipit sit amet dui. Aliquam in vehicula
      lorem. Praesent vitae vestibulum ante, nec vestibulum metus. Morbi commodo diam in leo semper ornare. Phasellus et diam magna.
      <cite>Inara Serra</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">9</strong>
    <blockquote class="content">
      Maecenas cursus ut erat vitae vestibulum. Fusce feugiat dignissim augue consequat condimentum. Donec risus felis, ultricies a velit sed, varius ullamcorper enim. Suspendisse ultrices non tortor non lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing
      elit.
      <cite>Jayne Cobb</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">4</strong>
    <blockquote class="content">
      Donec adipiscing lacus sed neque cursus ullamcorper. Vestibulum tellus lectus, molestie vitae augue et, egestas convallis mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec porttitor mi vitae mauris aliquam,
      non accumsan odio tincidunt. Aliquam semper enim quam, ac cursus lectus dignissim vitae. Suspendisse nec rutrum ligula.
      <cite>Kaylee Frye</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">7</strong>
    <blockquote class="content">
      Nullam et leo placerat lectus fringilla varius vel a lorem. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nibh eros, blandit at aliquam eu, ullamcorper eu diam. Etiam id viverra lacus, rutrum suscipit nulla. Maecenas adipiscing, mi sit
      amet iaculis congue, urna massa vestibulum tortor, a tempus nibh tortor id dui.
      <cite>Simon Tam</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">2</strong>
    <blockquote class="content">
      Maecenas semper, orci eget cursus aliquam, orci tellus sodales urna, nec varius nisi arcu gravida velit. Proin ultrices egestas nunc, eget dapibus erat sollicitudin in. Fusce fermentum dignissim ipsum sollicitudin tincidunt. Aliquam erat volutpat. Suspendisse
      in ornare ante.
      <cite>River Tam</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">10</strong>
    <blockquote class="content">
      Nullam purus ante, rhoncus ac malesuada at, bibendum nec urna. Cras lobortis viverra feugiat. Praesent sapien elit, sagittis vel orci sed, congue consequat nulla.
      <cite>Derrial Book</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">9</strong>
    <blockquote class="content">
      Donec malesuada semper lectus sed sagittis. Sed laoreet consectetur tortor, ac tempus ipsum malesuada non. Aenean dapibus leo sed sapien rhoncus, at dapibus ligula porta. Morbi tincidunt, urna eget ullamcorper aliquam, augue lectus placerat orci, tristique
      aliquet ipsum nisi id orci. Nulla vulputate lectus justo, eu dapibus lectus sodales ac. Donec volutpat nibh mi. Proin eu justo vitae dolor accumsan ultrices vel non ante.
      <cite>Sheriff Bourne</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">3</strong>
    <blockquote class="content">
      Sed consectetur, lorem vitae laoreet tempus, neque elit fringilla nisl, nec tempus urna quam eu nulla. Nunc tempor nec magna vel viverra. In dapibus aliquam velit, ut malesuada nibh ornare eget. Suspendisse in risus posuere, hendrerit odio id, tincidunt
      lacus. Nunc fermentum metus sit amet mauris pellentesque, vitae sollicitudin dui facilisis. Etiam at velit id dolor rhoncus porttitor. Vestibulum quis blandit felis.
      <cite>Lawrence Dobson</cite>
    </blockquote>
  </li>
  <li class="list-item">
    <strong class="score">7</strong>
    <blockquote class="content">
      Suspendisse in risus posuere, hendrerit odio id, tincidunt lacus. Nunc fermentum metus sit amet mauris pellentesque, vitae sollicitudin dui facilisis. Etiam at velit id dolor rhoncus porttitor. Vestibulum quis blandit felis.
      <cite>Jubal Early</cite>
    </blockquote>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需尝试上面的小提琴并逐个运行案例。并请在订单asc和desc按钮上调用函数

var ordering = 'asc' // or 'desc';

function sortEm(a,b){
  return parseInt($('strong.score', a).text()) > parseInt($('strong.score', b).text()) ? 1 : -1;
}

$('li').sort(sortEm).prependTo($('ul#list'));

答案 3 :(得分:0)

问题是,您尝试解析元素的innerHTMLparseInt函数返回所有节点的NaN。由于Array.prototype.sort函数不稳定,您将以随机顺序获取段落。

您可以做的最简单的事情是从innerText属性获取订单,因此文本将以数字开头(因为innerText删除所有HTML标记并仅保留文本),parseInt将成功解析数字。

但你真正需要的是获得innerText .score元素。