<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>E-commerce Website</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).on("change", ".price-sorting", function() {
var sortingMethod = $(this).val();
if(sortingMethod == 'l2h')
{
sortProductsPriceAscending();
}
else if(sortingMethod == 'h2l')
{
sortProductsPriceDescending();
}
});
function sortProductsPriceAscending() {
var products = $('.product-item');
products.sort(function(a, b){ return $(a).data("price-item")-$(b).data("price-item")});
$(".product-grid").html(products);
}
function sortProductsPriceDescending(){
var products = $('.product-item');
products.sort(function(a, b){ return $(b).data("price-item") - $(a).data("price-item")});
$(".product-grid").html(products);
}
</script>
</head>
<body>
<!-- Drop down for sorting prices -->
<select class="price-sorting selectBox" name="price-sorting">
<option>Relevance</option>
<option value="l2h">Price: Low - High</option>
<option value="h2l">Price: High - Low</option>
</select>
<!-- Products -->
<div class="product-grid">
<!-- Product 1 -->
<div class="product-item">
<img class="vr_headset_iphone_black" src="https://i1.wp.com/virtualrealitygearreview.com/wp-content/uploads/2018/01/41gXvNpslJL.jpg?fit=128%2C128">
<br>
<span class="vr_headset_item_1">Tepoinn 3D VR Glasses Headset</span>
<span class="vr_headset_item_2">Virtual Reality Box - Black</span>
<br>
<br>
<span class="price_item">£18.99</span>
<br>
<br>
<button onclick="add-to-basket" class="basket_item style_basket">ADD TO BASKET</button>
</div>
<!-- Product 2 -->
<div class="product-item">
<img class="vr_headset_iphone_red" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVpLUMNSvaIgOvm5DVg65fap-HzwBEyhJKU23KUCQj5QcUsKuC">
<br>
<span class="vr_headset_item_3">Maplin Pro VR Headset with HD</span>
<span class="vr_headset_item_4">Stereo Headphones - Red</span>
<br>
<br>
<span class="price_item">£39.99</span>
<br>
<br>
<button class="basket_item style_basket">ADD TO BASKET</button>
</div>
</div>
</body>
</html>
我正在创建一个电子商务网站,我正在尝试按价格(低 - 高 - 高 - 低)对产品进行分类。但是,我使用的JQuery代码不起作用。我研究了如何解决这个问题,并使用了website上发布的示例代码,但代码仍然不适用于我。 点击此处查看代码 - JSFiddle
答案 0 :(得分:0)
根据您的javascript,您的product-item
应该有一个data-price-item
属性用于排序。
您应该将该属性放在它所属的位置
<div class="product-item" data-price-item="18.99">