如何根据某个类的元素中的文本对包含HTML的jQuery数组进行排序

bxjv4tth  于 2022-12-22  发布在  jQuery
关注(0)|答案(1)|浏览(123)

我有一个包含HTML代码的数组,我需要将这些代码附加到页面的某个地方。这些是文本消息,我试图将它们按日期排序。

我看了一些不同的帖子,其中描述了使用jQuery.sort(),我已经尝试在这里实现它:

function sortHtmlArray(array) {
    array.sort((a, b) => a.find('.incoming-message-date') - b.find('.outgoing-message-date'));
}

但我显然没有做正确的,因为它仍然排序如下(无序)。
我哪里做错了?

vktxenjb

vktxenjb1#

也许这个?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <p>Not Ordered:</p>
    <div style="border: 1px solid black" class="not-ordered-msg-container"></div>
    <br />
    <p>Ordered:</p>
    <div style="border: 1px solid black" class="ordered-msg-container"></div>

    <script>
      const html = `
        <div class="col">
            <div class="incoming-message-date">2022-12-01 08:00</div>
            <div class="incoming-message-box">3º message (incomming)</div>
            <br/>
        </div><div class="col">
          <div class="incoming-message-date">2021-06-26 13:00</div>
          <div class="incoming-message-box">2º message (incomming)</div>
          <br/>
        </div><div class="col">
          <div class="incoming-message-date">2026-04-08 15:00</div>
          <div class="incoming-message-box">6º message (incomming)</div>
          <br/>
        </div><div class="col">
          <div class="incoming-message-date">2020-04-08 14:00</div>
          <div class="incoming-message-box">1º message (incomming)</div>
          <br/>
        </div><div class="col">
          <div class="incoming-message-date">2026-04-08 14:00</div>
          <div class="incoming-message-box">5º message (incomming)</div>
          <br/>
        </div><div class="col">
          <div class="outgoing-message-date">2023-12-01 08:00</div>
          <div class="incoming-message-box">4º message (outgoing)</div>
          <br/>
        </div>`;

      const notOrdered = $(html);
      notOrdered.appendTo($(".not-ordered-msg-container"));

      const ordered = $(html);
      ordered.sort(function (a, b) {
        const A = $(a).find(".outgoing-message-date, .incoming-message-date").text();
        const B = $(b).find(".outgoing-message-date, .incoming-message-date").text();

        return A.localeCompare(B);
      });
      $(ordered).appendTo($(".ordered-msg-container"));
    </script>
  </body>
</html>

相关问题