根据姓氏的字母顺序自动对卡片进行排序

时间:2018-04-05 23:22:17

标签: javascript jquery html css3

我正在尝试对这些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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

以下函数Sort使用其子节点.card

对所有.lname进行排序

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

&#13;
&#13;
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)
&#13;
img {
  width: 5% !important;
}
&#13;
<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>
&#13;
&#13;
&#13;