好吧,我正在尝试这样做,以便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
函数但是我只能在顶部获得最高价值,任何建议?
答案 0 :(得分:3)
根据他们的divs
对包装器data('worth')
进行排序,然后将已排序的列表追加到包装器中:
$('button').click(function() {
$('.wrapper div').sort(function(a, b) {
return $(b).data('worth') - $(a).data('worth');
}).appendTo('.wrapper');
});
&#13;
<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>
&#13;
答案 1 :(得分:0)
//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>
答案 2 :(得分:0)
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