开发者

How to sort a list based on the number within each LI.span?

I'm trying to sort the list of LI's based on the number that's in the span within each LI. I've looked at plugins that can do this but that's not what I want.

开发者_如何学Python

Can someone show me how you would sort a simple list how I stated above? I really don't have any idea where to even start, I don't know if it's complex or simple.

Here is my code:

ul {
  width: 200px;
  background-color: #252525;
  padding: 10px;
}

li {
  background-color: #353535;
  margin: 10px;
  padding: 5px;
  color: #fff;
}

li span {
  float: right;
}
<ul>

  <li> Cups
    <span>12</span>
  </li>

  <li> Plates
    <span>18</span>
  </li>

  <li> Forks
    <span>03</span>
  </li>

  <li> Knives
    <span>06</span>
  </li>

  <li> Bowls
    <span>08</span>
  </li>

</ul>


Here is what you should use:

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

$('li').sort(sortEm).prependTo($('ul#test'));
ul {
  width: 200px;
  background-color: #252525;
  padding: 10px;
}

li {
  background-color: #353535;
  margin: 10px;
  padding: 5px;
  color: #fff;
}

li span {
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test">

  <li> Cups
    <span>12</span>
  </li>

  <li> Plates
    <span>18</span>
  </li>

  <li> Forks
    <span>03</span>
  </li>

  <li> Knives
    <span>06</span>
  </li>

  <li> Bowls
    <span>08</span>
  </li>

</ul>


You should fill an array with all the <li> elements, sort this array using sort(), then empty() the list add append() the sorted elements.

Something like this :

$("#doSort").click(function() {
  // store the li items
  var items = $('ul li').get();

  items.sort(function(a, b) {
    var valueA = $(a).find("span").text();
    var valueB = $(b).find("span").text();

    if (valueA < valueB) return -1;
    if (valueA > valueB) return 1;
    return 0;
  });
  // clear the list and re-add sorted items on button click 
  $("ul").empty().append(items);
});
ul {
  width: 200px;
  background-color: #252525;
  padding: 10px;
}

li {
  background-color: #353535;
  margin: 10px;
  padding: 5px;
  color: #fff;
}

li span {
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li> Cups
    <span>12</span>
  </li>

  <li> Plates
    <span>18</span>
  </li>

  <li> Forks
    <span>03</span>
  </li>

  <li> Knives
    <span>06</span>
  </li>

  <li> Bowls
    <span>08</span>
  </li>

</ul>

<button id="doSort">Sort this list!</button>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜