我已经设法在我的商店网站上添加了一个按钮,该按钮按价格对产品进行分类(不太了解javascript)。
我希望它更新按钮中的文本,以向用户传达按价格排序是升序还是降序,例如:'按价格排序:升序'
排序按钮的html:
<button type="button" class="btn btn-outline-secondary">
<a class="sortByPrice" href="#art-for-sale">Sort by Price</a>
</button>
这是第一个产品的html:
<div class="row results">
<div class="col-md-4 product">
<div class="card mb-4 shadow-sm">
<img src='images_organised_small/for_sale_small/3opera_house_night_500.jpg'>
<div class="card-body">
<span class="card-text title">Opera House Night</span>
<p class="card-text price">$500</p>
<p class="card-text description">insert artwork description here not too long but not too short!</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" onClick="window.open('https://www.paypal.me/meredithscott4/500');" class="btn btn-sm btn-outline-secondary">Buy</button>
<button type="button" onClick="window.open('images_organised_large/for_sale_large/3opera_house_night_500.jpg');" class="btn btn-sm btn-outline-secondary">View</button>
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
这是javascript
var ascending = false;
$('.tab-content').on('click', '.sortByPrice', function() {
var sorted = $('.product').sort(function(a, b) {
return (ascending ==
(convertToNumber($(a).find('.price').html()) <
convertToNumber($(b).find('.price').html()))) ? 1 : -1;
});
ascending = ascending ? false : true;
$('.results').html(sorted);
});
var convertToNumber = function(value) {
return parseFloat(value.replace('$', ''));
}
使用jQuery的.html()
:
var ascending = false;
$('.tab-content').on('click', '.sortByPrice', function() {
var sorted = $('.product').sort(function(a, b) {
return (ascending ==
(convertToNumber($(a).find('.price').html()) <
convertToNumber($(b).find('.price').html()))) ? 1 : -1;
});
if(ascending){
ascending = false;
$(".sortByPrice").html("Sort by Price: descending");
}else{
ascending = true;
$(".sortByPrice").html("Sort by Price: ascending");
}
$('.results').html(sorted);
});
var convertToNumber = function(value) {
return parseFloat(value.replace('$', ''));
}