我的项目和你的类似,所以请填写下面的空白。
创建一个集合模板collection.price-filter.liquid
使用 ajax 来获取产品 json。当然有 250 个限制。如果超过 250 个,则需要先使用应用程序过滤结果。或者,只使用多个请求。
<script>
var allProducts;
var filteredProducts = [];
var activeFilter = [];
$(document).ready(function(){
var url = '{{collection.url}}/products.json?limit=250';
const res = getProducts(url);
});
function getProducts(url){
$.ajax({
type: 'GET',
url: url,
success: function(res){
allProducts = res.products;
filterProducts(allProducts);
},
error: function(status){
alert(status);
}
});
}
</script>
过滤产品以填充filteredProducts
数组对象
//loop through the products, create categories ($20-$40, $40-$60, etc.)
function filterProducts(products){
var cat1 = '20-40', cat2 = '40-60';
var currentCat;
products.forEach(function (i, j){
if (i.price > 20 && i.price <= 40){
currentCat = cat1;
else if (i.price > 40 && i.price <= 60) {
currentCat = cat2;
}
if(filteredProducts[currentCat]){
filteredProducts[currentCat].push(i);
}
else {
filteredProducts[currentCat] = [i]
}
};
});
}
生成后filteredProducts
,听取checkbox
用户的选择,将其添加selection
到一个名为的数组中activeFilter
function getActiveFilter(){
$('#myFilter').each(function(){
if($(this).is(':checked')){
//add to activeFilter
}
});
}
生成resultFilter
自filteredProducts
和activeFilter
,消除共同结果;
function resultFilter(){
var result = [];
activeFilter.forEach(function (i, value){
Object.keys(value).forEach(function(j, product){
//add to result
};
});
}
使用handlebars.js构建/显示产品结果
<script id="ProductTemplate" type="text/x-handlebars-template">
{% raw %}
{{#product}}
<div class="col">
<a href="/products/{{productHandle}}" class="grid__image">
<div class="product__image-wrapper" style="background-color: white;">
<img class="no-js lazyload" width="316" height="237"
data-src="{{ featuredImg }}"
data-widths="[108, 360, 375, 414, 568, 684, 720, 732, 736, 768, 1024, 1200, 1296, 1512, 1728, 1944, 2048]"
data-aspectratio="1.33"
data-sizes="auto"
data-parent-fit="width"
alt="{{ title }}">
</div>
</a>
<p class="h5"><a href="/products/{{productHandle}}">{{ title }}</a></p>
</div>
{{/product}}
{% endraw %}
</script>
将数据插入#container-products
,您希望在其中显示过滤后的产品。
function buildFilteredProducts(filteredProds) {
var $productContainer = $('#container-product');
$productContainer.empty();
if(filteredProds.length <= 0){
$productContainer.append('empty result');
return;
}
var products = [];
var product = {};
var data = {};
var source = $("#ProductTemplate").html();
var template = Handlebars.compile(source);
products = filteredProds.map(function(productItem) {
return product = {
id: productItem.id,
title: decodeHtml(productItem.title),
featuredImg: responsiveImage(productItem.images[0].src),
productHandle: productItem.handle
}
});
data = {
product: products
}
$productContainer.append(template(data));
}