我试图对这些UI卡进行排序,以根据它们使用Jquery所包含的姓氏(.lname)以字母顺序显示。



<div class="main">

  <div class="card">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><span class="lname">John</span> <span class="fname">Ike</span></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

  <div class="card">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><span class="lname">Mark</span> <span class="fname">Amos</span></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

   <div class="card">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><span class="lname">Apple</span> <span class="fname">Joshua</span></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

</div>

最佳答案

以下函数Sort用其子节点.card对所有.lname进行排序

localeCompare确定两个字符串在当前语言环境中是否相等。 from MSDN



function Sort() {
  var sortedCards = $('.card').sort(function(a, b) {
    return $(a).find('.lname').text().localeCompare($(b).find('.lname').text())
  })
  $('.main').remove('.card').append(sortedCards)
}

$('.sort_button').on('click',Sort)

img {
  width: 5% !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="button" class="sort_button" value="Click!">
  <div class="card">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><span class="lname">John</span> <span class="fname">Ike</span></h4>
      <p>Architect & Engineer(John)</p>
    </div>
  </div>

  <div class="card">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><span class="lname">Mark</span> <span class="fname">Amos</span></h4>
      <p>Architect & Engineer(Mark)</p>
    </div>
  </div>

  <div class="card">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><span class="lname">Apple</span> <span class="fname">Joshua</span></h4>
      <p>Architect & Engineer(Apple)</p>
    </div>
  </div>

</div>

关于javascript - 根据姓氏的字母顺序自动对卡片分类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49682976/

10-13 06:17