我試圖按價格和評分對結果列表進行排序。爲了簡單起見,我剛剛收錄了2個結果:Rider's Lodge和Olina Lodge。我寫了一個可以單向排序的函數。jQuery按升序和降序排序(不是表格)
如何重新使用相同的函數對我的結果進行排序,以便點擊'按價格排序'按升序排序,再次點擊它按降序排序並在兩者之間切換?
<div class="tab-content">
<div id="filters">
<p>
<a href="javascript:sort_by_rating();">Sort by Rating</a>
<br>
<a href="javascript:sort_by_price();">Sort by Price</a>
</p>
</div>
<div id="div_hotel_results" class="tab-pane active">
<form id="hotel-form">
...
</form>
<div class="results-row">
<h5>Riders Lodge</h5>
<span class="label label-info price">$103.64</span>
<span class="rating" data-rating="3.0">3.0</span>
</div>
<div class="results-row">
<h5>Olina Lodge</h5>
<span class="label label-info price">$99.64</span>
<span class="rating" data-rating="2.5">2.5</span>
</div>
</div>
</div>
<script type="text/javascript">
function sort_by_price() {
var sorted_list = [];
$('.price').each(function (index) {
sorted_list[index] = $(this).parent().parent().remove();
sorted_list[index]['cleaned_price'] = parseFloat($(this).text().replace(/[^0-9\.]+/g,""));
});
sorted_list.sort(function (a, b) {
if (a['cleaned_price'] == b['cleaned_price']) {
return 0;
} else if (a['cleaned_price'] > b['cleaned_price']) {
return 1;
} else {
return -1;
}
});
$('#hotel-form').after(sorted_list);
}
</script>
你想要的功能評價/價格之間既升序排序,desceding和開關? – 2013-03-24 15:34:51