如何按 jquery 列表的 child 元素中的 id 排序

How to sort by id in child element of a list in jquery

对代码非常陌生,只真正尝试基础知识。

我需要按发布日期排序此列表,selecting child 元素的 class (.date),然后使用 id 进行排序。请记住 li 的 id 用于按其他内容排序。我只是不知道如何 select child 的 class,以及如何按 child 的 id 排序。

这是标记:

<button id="datereleased">Date Released</button>

<div id="sortcontainer">

 <li id="60">
  <h2>Some game</h2>
  <h2 class="date" id="2015">(2015)</h2>  
  <h3>45/100</h3>
  </li>

 <li id="45">
  <h2>Some game</h2>
  <h2 class="date" id="2017">(2017)</h2>
  <h3>45/100</h3>
  </li>

 <li id="80">
  <h2>Some game</h2>
  <h2 class="date" id="2013">(2013)</h2>
  <h3>45/100</h3>
  </li>
</div>

以及我目前拥有的:

$(document).ready(function() {
    $( "#datereleased" ).click(function(){
        var lis = $('#sortcontainer').children('li').remove();    
        lis.sort(function(a, b) {
            return parseInt($('.date > id', a)) >  parseInt($('.date > id', b));
        }); 
        $('#sortcontainer').append(lis);
    });
});

如果有人有任何信息,请提前致谢

从日期中获取 id 属性以进行排序。

$('#datereleased').on('click', function(){
  var $sortContainer = $('#sortcontainer');
  
  $sortContainer.append(
    $sortContainer.children().sort(function(a, b){
      return (
        parseInt($('.date', a).attr('id'), 10)
        -
        parseInt($('.date', b).attr('id'), 10)
      );
    }).get()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="datereleased">Date Released</button>

<div id="sortcontainer">
  <li id="60">
    <h2>Some game</h2>
    <h2 class="date" id="2015">(2015)</h2>
    <h3>45/100</h3>
  </li>

  <li id="45">
    <h2>Some game</h2>
    <h2 class="date" id="2017">(2017)</h2>
    <h3>45/100</h3>
  </li>

  <li id="80">
    <h2>Some game</h2>
    <h2 class="date" id="2013">(2013)</h2>
    <h3>45/100</h3>
  </li>
</div>

您需要修复您的选择器以定位具有 date class 和 idh2 元素,而不是定位具有名为 [= 的标签的元素14=].

然后您可以通过对 id 属性的值执行减法来对其进行排序,并追加 li 祖先。

此示例不使用 jQuery,而是使用更新的语法,如箭头函数:

document.addEventListener("DOMContentLoaded", function() {
  document.querySelector("#datereleased").addEventListener("click", function() {
      var sc = document.querySelector("#sortcontainer");

      Array.from(sc.querySelectorAll('li > .date[id]'))
        .sort((a, b) => a.id - b.id)
        .forEach(el => sc.appendChild(el.closest("li")));
    });
});
<button id="datereleased">Date Released</button>

<div id="sortcontainer">

  <li id="60">
    <h2>Some game</h2>
    <h2 class="date" id="2015">(2015)</h2>
    <h3>45/100</h3>
  </li>

  <li id="45">
    <h2>Some game</h2>
    <h2 class="date" id="2017">(2017)</h2>
    <h3>45/100</h3>
  </li>

  <li id="80">
    <h2>Some game</h2>
    <h2 class="date" id="2013">(2013)</h2>
    <h3>45/100</h3>
  </li>
</div>