簡體   English   中英

基於jQuery中的數據屬性對div進行排序

[英]Sorting a div based on data attribute in jQuery

好吧,我正試圖這樣做,所以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函數但是我只能在頂部獲得最高價值,任何建議?

根據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> 

 //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> 

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM