【问题标题】:Sorting a div based on data attribute in jQuery根据jQuery中的数据属性对div进行排序
【发布时间】:2018-02-06 05:55:35
【问题描述】:

好的,我正在尝试让 jQuery 在单击按钮时对 div 进行排序,

假设列表如下所示,

<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

然后按钮被点击后我希望它吐出来,

   <div class="wrapper">
      <div class="item" data-worth="720">Edgy</div>
      <div class="item" data-worth="666">Meme</div>
      <div class="item" data-worth="420">Blaze</div>
    </div>

基本上将价值从低到高排序,重新排列所有内容并将其放回包装中。

老实说,我对如何继续这样做一无所知,我想使用 jQuery 的 .each 函数,但我只能在顶部获得最高值,有什么建议吗?

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

根据data('worth') 对包装器的divs 进行排序,然后将排序后的列表附加回包装器:

$('button').click(function() {
  $('.wrapper div').sort(function(a, b) {
    return $(b).data('worth') - $(a).data('worth');
  }).appendTo('.wrapper');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Sort</button>
<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

【讨论】:

    【解决方案2】:

    //code taken from: https://stackoverflow.com/questions/6133723/sort-divs-in-jquery-based-on-attribute-data-sort
    
    //All I have done is, presented the code such a way that it is easy for you to understand and use it in your application
    
    function asc_sort(a, b){ return ($(b).data("worth")) > ($(a).data("worth")) ? 1 : -1; }
    
    jQuery.fn.sortDivs = function sortDivs() {
        $(".item", this[0]).sort(asc_sort).appendTo(this[0]);
    }
    
    $('#BtnSort').on('click', function(){
        $(".wrapper").sortDivs();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button type="button" id="BtnSort">Sort</button>
    <div class="wrapper">
      <div class="item" data-worth="720">Edgy</div>
      <div class="item" data-worth="420">Blaze</div>
      <div class="item" data-worth="666">Meme</div>
    </div>

    【讨论】:

      【解决方案3】:

      HTML:

      <div class="wrapper">
        <div class="item" data-worth="720">Edgy</div>
        <div class="item" data-worth="420">Blaze</div>
        <div class="item" data-worth="666">Meme</div>
      </div>
      <button class="clickMe">Sort</button>
      

      JavaScript:

      function someFunction(){
        var $wrapper = $('.wrapper');
          $wrapper.find('.item').sort(function (a, b) {
          return +b.dataset.worth - a.dataset.worth;
      })
      .appendTo( $wrapper );
      }
      $('body').on('click', '.clickMe', someFunction);
      

      这是一个工作:JSFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-02
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多