pin*_*nkp 2 sorting select filter jquery-isotope
我正在使用 Isotope 对产品页面进行排序、过滤和搜索。到现在为止还挺好。我被困在几个领域。我无法在网上找到包含我需要的确切功能组合的示例,因此需要一些帮助。
简而言之,我有多个选择下拉过滤产品,选择价格排序顺序和快速搜索输入字段。所有的工作,但我有一些需要的修正。
去做:
过滤后搜索不起作用。我需要它与过滤器一起工作。
在价格选择下拉菜单中添加了按“销售”和“新品”排序的功能。
添加 URL 哈希侦听器以创建用于过滤的链接,即首先排序的 New In 链接。
我当前用于过滤和排序的 JS:
$(document).ready(function(){
// quick search regex
var qsRegex;
var filterValue;
// init Isotope
var $grid = $(".grid").isotope({
itemSelector: ".grid-item",
layoutMode: "fitRows",
getSortData: {
price: '.t-price parseInt',
category: '[data-category]',
},
filter: function() {
var $this = $(this);
var searchResult = qsRegex ? $this.text().match(qsRegex) : true;
var selectResult = filterValue ? $this.is(filterValue) : true;
return searchResult && selectResult;
}
});
// bind filter on select change
//$(".filter-select").on("change", function() {
// get filter value from option value
// filterValue = $(this).val();
//console.log(filterValue);
//$grid.isotope();
//});
// store filter for each group
var filters = {};
$('.filter-select').on( 'change', function( event ) {
var $select = $( event.target );
// get group key
var filterGroup = $select.attr('value-group');
// set filter for group
filters[ filterGroup ] = event.target.value;
// combine filters
var filterValue = concatValues( filters );
// set filter for Isotope
$grid.isotope({ filter: filterValue });
});
// flatten object by concatting values
function concatValues( obj ) {
var value = '';
for ( var prop in obj ) {
value += obj[ prop ];
}
return value;
}
$('#price-sort').on( 'change', function() {
var type = $(this).find(':selected').attr('data-sorttype');
console.log(type);
var sortValue = this.value;
if(type=='ass'){$grid.isotope({ sortBy: sortValue , sortAscending: false});}
else{$grid.isotope({ sortBy: sortValue , sortAscending: true});}
$grid.isotope({ sortBy: sortValue });
});
// change is-checked class on buttons
$('#price-sort').on( 'change', function() {
var sortByValue = this.value;
console.log(sortByValue);
$grid.isotope({ sortBy: sortByValue});
});
// use value of search field to filter
var $quicksearch = $(".quicksearch").keyup(
debounce(function() {
qsRegex = new RegExp($quicksearch.val(), "gi");
$grid.isotope();
})
);
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
return function debounced() {
if (timeout) {
clearTimeout(timeout);
}
function delayed() {
fn();
timeout = null;
}
setTimeout(delayed, threshold || 100);
};
}
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<div id="sort-filter">
<div id="sort">
<select id="price-sort" class="select-css form-control long">
<option selected disabled class="s-title"> Sort </option>
<option data-sorttype="dec" value="price">£ Low To High</option>
<option data-sorttype="ass" value="price">£ High To Low</option>
</select>
</div>
<div class="filters">
<select class="filter-select select-css short" value-group="sizes" id="sizes">
<option selected disabled class="s-title"> Size </option>
<option value="*">All</option>
<option value=".XS">XS</option>
<option value=".S">S</option>
<option value=".M">M</option>
<option value=".L">L</option>
<option value=".XL">XL</option>
<option value=".XXL">XXL</option>
</select>
</div>
</div>
<div class="container">
<ul class="grid cs-style-3">
<div class="grid-sizer"></div>
<li class="grid-item XS Male Beige Bags Mint">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="hat sale item">
</figure>
<div id="pro-deets">
<h3>hat sale item</h3>
<span id="price" class="holderpage">
£<span class="price t-price">3</span>
</span>
</div></a>
</li>
<li class="grid-item L Female Brown Tops Worn">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="product no sale no new">
</figure>
<div id="pro-deets">
<h3>product no sale no new</h3>
<span id="price" class="holderpage">
£<span class="price t-price">40</span>
</span>
</div></a>
</li>
<li class="grid-item L Female Brown Tops Worn New" data-category="New">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="Skirt">
</figure>
<div id="pro-deets">
<h3>Skirt</h3>
<span id="price" class="holderpage">
£<span class="price t-price">10</span>
</span>
</div></a>
</li>
<li class="grid-item XS Male Beige Bags Mint Sale" data-category="Sale">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="Jacket">
</figure>
<div id="pro-deets">
<h3>Jacket</h3>
<span id="price" class="holderpage">
£<span class="price sale">30</span>
<span class="price">£<span class="t-price">20</span></span>
</span>
</div></a>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个两部分的答案。从不同的答案中检查第 2 部分。
当我阅读您的代码时,您走在正确的轨道上。由于搜索和过滤器不能在您的代码中一起工作的原因,问题在于,当您初始化 $grid 时,您为 $grid 定义了一个过滤器函数。但是,当“选择过滤器”组有更改时,通过调用$ grid.isotope({filter:filtervalue})重新定义该过滤器。当您使用任何可配置值调用 $grid.isotope() 时,$grid 将采用这些新配置。
因此,您问题的答案只是有两个变量。一个用于存储过滤器值,另一个用于存储搜索值。每当 $grid.isotope() 被调用时,它只会使用这两个值进行过滤。
您的代码还有其他一些问题。您不需要进行两次价格排序。那只需要做一个。当涉及到 HTML、类和 id 时,一个 id 应该只出现在一个页面中。这意味着,您不能有两个具有相同 ID 的部门。如果它不重要,它可能不会破坏您的页面。但是,在以编程方式操作页面时,这可能会破坏您的页面。除此之外,您使用过滤器选择的方式是为了从两个按钮组中获取值。但它可以用于您的情况,我想您将来可能会需要它,因为除了尺寸之外,可能还会有颜色等......此外,在比较 JS 中的字符串以进行价格排序时。最好用 === 比较字符串是否相等。在JS中比较字符串可以参考这个在 JavaScript 比较中应该使用哪个等于运算符 (== vs ===)?.
对于代码设计,你可以这样做。我认为将所有内容放在 document.ready() 中的方式将使代码运行得更快。
对于答案代码,例程很简单。当文档准备好时,与搜索字段和选择字段相关联的所有事件都将被初始化。之后,filterWithHash() 函数被绑定到 onhashchange 事件。然后执行该函数以初始化网格,同时检查任何关联哈希的 URL。
对于 URL 中的哈希,请尝试“filter=”和“search=”。它们可以一起使用,没有任何问题。您还可以将该函数转换为不仅能够采用散列而且能够采用 get 参数。
代码中还有一些注释可能会对您有所帮助。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
<script>
$(document).ready(function(){
// Quick Search Regex
var qsRegex;
// Filter Value
var filterValue;
// Grid not initialize yet.
var $grid;
// Since there is only one filter group and that is sizes.
// It isn't necessary to be done like this.
// Just grab the selected value everytime the sizes select is changed.
// However, this was still left like this.
$('.filter-select').on( 'change', function( event ) {
// Hold the filter values here.
var filters = {};
var $select = $( event.target );
// Get group key
var filterGroup = $select.attr('value-group');
// Set filter for group
filters[ filterGroup ] = event.target.value;
// Assign the filter value to the global filterValue
filterValue = concatValues( filters );
// Execute $grid.isotope() to update with current global filter value.
$grid.isotope();
});
// flatten object by concatting values
function concatValues( obj ) {
var value = '';
for ( var prop in obj ) {
value += obj[ prop ];
}
return value;
}
// change is-checked class on buttons
// Only need one price-sort not two
$('#price-sort').on( 'change', function() {
var type = $(this).find(':selected').attr('data-sorttype');
// REMEMBER TO TAKE THE CONSOLE LOG OUT IN PRODUCTION
console.log(type);
var sortValue = this.value;
if( type === 'asc' ) $grid.isotope({ sortBy: sortValue , sortAscending: false});
else $grid.isotope({ sortBy: sortValue , sortAscending: true});
$grid.isotope({ sortBy: sortValue });
});
// use value of search field to filter
var $quicksearch = $("#quicksearch").keyup(
debounce(function() {
qsRegex = new RegExp($quicksearch.val(), "gi");
// Every time qsRegex is update do $grid.isotope() to update
// The filter with global filterValue and qsRegex
$grid.isotope();
})
);
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
return function debounced() {
if (timeout) {
clearTimeout(timeout);
}
function delayed() {
fn();
timeout = null;
}
setTimeout(delayed, threshold || 100);
};
}
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match( /filter=([^&]+)/i );
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent( hashFilter );
}
function getSearchFilter() {
// get search=filterName
var matches = location.hash.match( /search=([^&]+)/i );
var searchFilter = matches && matches[1];
return searchFilter && decodeURIComponent( searchFilter );
}
/*
* This function below can be customize to utilize not just only hashes
* but also "Get Requests"
*/
function filterWithHash() {
var hashFilter = getHashFilter();
var searchFilter = getSearchFilter();
if ( !searchFilter && !hashFilter && $grid ) {
return;
}
// If hashFilter is there, utilize it.
if ( hashFilter ) {
var selectValue = $('select[id="sizes"]').find('option[value="'+ hashFilter +'"]');
// Only search for a value if it is found within the select fields, else disregard it.
if ( selectValue.length > 0 ){
selectValue.prop('selected', 'selected');
filterValue = hashFilter;
}
}
// If searhFilter is there, utilize it.
if ( searchFilter) {
$('#quicksearch').val(searchFilter);
qsRegex = new RegExp(searchFilter, "gi");
}
/* If $grid is not initialize, it will get initialize.
* This will only happen on first run.
* One grid is initilized, everytime grid.isotope() is run
* without any value, grid will be updated to what initilized below.
* Thus, each later run of isotope(), the filter will look at both,
* the searchResult and the qsRegex if they are available.
*/
if ( !$grid ) {
$grid = $(".grid").isotope({
itemSelector: ".grid-item",
layoutMode: "fitRows",
getSortData: {
price: '.t-price parseInt',
category: '[data-category]',
},
filter: function() {
var $this = $(this);
var searchResult = qsRegex ? $this.text().match(qsRegex) : true;
var selectResult = filterValue ? $this.is(filterValue) : true;
return searchResult && selectResult;
}
});
} else $grid.isotope();
}
/*
* Trigger filter with hash to initialize grid
* and also to check the url for hash.
*/
filterWithHash();
// Bind the filterWithHash function to the hashchange event.
$(window).on( 'hashchange', filterWithHash );
});
</script>
</head>
<body>
<p><input type="text" id="quicksearch" placeholder="Search" /></p>
<div id="sort-filter">
<!-- Short Div -->
<div id="sort">
<select id="price-sort" class="select-css form-control long">
<option selected disabled class="s-title"> Sort </option>
<option data-sorttype="des" value="price">£ Low To High</option>
<option data-sorttype="asc" value="price">£ High To Low</option>
</select>
</div>
<!-- Filter Div -->
<div class="filters">
<select class="filter-select select-css short" value-group="sizes" id="sizes">
<option selected disabled class="s-title"> Size </option>
<option value="*">All</option>
<option value=".XS">XS</option>
<option value=".S">S</option>
<option value=".M">M</option>
<option value=".L">L</option>
<option value=".XL">XL</option>
<option value=".XXL">XXL</option>
</select>
</div>
</div>
<div class="container">
<ul class="grid cs-style-3">
<div class="grid-sizer"></div>
<li class="grid-item XS Male Beige Bags Mint">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="hat sale item">
</figure>
<div id="pro-deets"> <!-- This should not be id -->
<h3>hat sale item</h3>
<span id="price" class="holderpage"> <!-- This should not be id -->
£<span class="price t-price">3</span>
</span>
</div>
</a>
</li>
<li class="grid-item L Female Brown Tops Worn">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="product no sale no new">
</figure>
<div id="pro-deets">
<h3>product no sale no new</h3>
<span id="price" class="holderpage">
£<span class="price t-price">40</span>
</span>
</div>
</a>
</li>
<li class="grid-item L Female Brown Tops Worn New" data-category="New">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="Skirt">
</figure>
<div id="pro-deets">
<h3>Skirt</h3>
<span id="price" class="holderpage">
£<span class="price t-price">10</span>
</span>
</div>
</a>
</li>
<li class="grid-item XS Male Beige Bags Mint Sale" data-category="Sale">
<a href="link" class="animsition-link" data-animsition-out-class="fade-out-left-lg">
<figure style="background-image: URL(image.jpg);">
<img src="/image2.jpg" alt="Jacket">
</figure>
<div id="pro-deets">
<h3>Jacket</h3>
<span id="price" class="holderpage">
£<span class="price sale">30</span>
<span class="price">£<span class="t-price">20</span></span>
</span>
</div>
</a>
</li>
</ul>
</div>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
我被限制为 30000 个字符。因此,我删除了示例 2 中的 HTML 部分。只需将示例 1 的 JS 替换为示例 2 中的 JS 即可运行示例 2。
对于第二个示例,它的例程几乎与第一个示例相似。对于第二个示例,每当用户选择与网格的过滤操作相关联的任何字段时,所选值都会应用于网格。之后,这些值将应用于 location.hash。防止 filterWithHash() 运行和解释刚刚创建的哈希。setHash() 函数将调用 gridAlreadyUpdated 的变量设置为 true 以告诉 filterWithHash() 不需要更新任何内容。
setHash() 函数将仅解释与过滤操作关联的哈希参数。其他哈希值被忽略。
我还写在代码中的其他注释可能可以帮助您。
"use strict";
$(document).ready(function(){
// Quick Search Regex
var qsRegex;
// Filter Value
var filterValue;
// sortValue & whether to sortAscending
var sortValue;
var sortAscending;
// Grid not initialize yet.
var $grid;
// Last state of all the filters
var lastState = {};
/*
* Parameter name for quicksearch, filter, and sort
* Have this here so everything can easily be changed in one place.
*
*/
var quicksearchParamName = "search";
var filterParamName = "filter";
var sortValueParamName = "sort";
var sortTypeParamName = "sorttype";
/*
* Regexes for grabbing values from hash parameter.
*
*/
var quicksearchRegex = RegExp(quicksearchParamName + '=([^&]+)', 'i');
var filterRegex = RegExp(filterParamName + '=([^&]+)' , 'i');
var sortValueRegex = RegExp(sortValueParamName + '=([^&]+)' , 'i');
var sortTypeRegex = RegExp(sortTypeParamName + '=([^&]+)' , 'i');
/*
* This variable is for the setHash() function to communicate with
* the filterWithHash() function.
*
* There isn't a need to build a hash string, update everything, and then
* reinterprete that same hash string right after.
*
* Thus, there isn't a need to run setHash() and then let filterWithHash()
* run on hash update.
*/
var gridAlreadyUpdated = false;
// use value of search field to filter
var $quicksearch = $("#quicksearch").keyup(
debounce(function() {
setHash(1);
})
);
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
return function debounced() {
if (timeout) {
clearTimeout(timeout);
}
function delayed() {
fn();
timeout = null;
}
setTimeout(delayed, threshold || 100);
};
}
/*
* Since there is only one filter group and that is sizes.
* It isn't necessary to be done like this.
* Just grab the selected value everytime the sizes select is changed.
* However, this was still left like this.
*
*/
$('.filter-select').on( 'change', function( event ) {
// Hold the filter values here.
var filters = {};
var $select = $( event.target );
// Get group key
var filterGroup = $select.attr('value-group');
// Set filter for group
filters[ filterGroup ] = event.target.value;
// Assign the filter value to the global filterValue
filterValue = concatValues( filters );
// Execute $grid.isotope() to update with current global filter value.
setHash(2);
});
// flatten object by concatting values
function concatValues( obj ) {
var value = '';
for ( var prop in obj ) {
value += obj[ prop ];
}
return value;
}
/*
* change is-checked class on buttons
* Only need one price-sort not two
*
*/
$('#price-sort').on( 'change', function() {
setHash(3, this);
});
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match( filterRegex );
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent( hashFilter );
}
function getSearchFilter() {
// get search=filterName
var matches = location.hash.match( quicksearchRegex );
var searchFilter = matches && matches[1];
return searchFilter && decodeURIComponent( searchFilter );
}
/*
* Get the sort param. This function will always return an array with
* 2 indexes. If both sortValue and sortType is found then it will return
* the values for both. Value is index 1, and type is index 2.
*
* For everything else, this function will return [null, null].
*/
function getSortParam() {
var valueMatches = location.hash.match( sortValueRegex );
var typeMatches = location.hash.match( sortTypeRegex );
var v = valueMatches && valueMatches[1];
var t = typeMatches && typeMatches[1];
if ( v && t ) return [decodeURIComponent( v ), decodeURIComponent( t )];
return [ null, null ];
}
/*
* This function will set the hash when one of the filtering field is
* changed.
*
* Parameter whocall is utilize to know who is the caller. There can only
* be one caller at a time. Whocall is utilize as int because comparing
* int is much faster than comparing string.
*
* whocall(1) = quicksearch
* whocall(2) = filter
* whocall(3) = sorting
*
* In a secure environment any other whocall besides the 3 above should
* generate an error.
*/
function setHash( whocall, obj ){
var hashes = {};
var hashStr = "";
/*
* Regex can also be utilized here to change the hash string, but for
* example, I thought this method look more clear.
*
* For performance, I haven't tested regEx vs this, so I don't know.
* Other method are available like URLSearchParams etc... but those method
* might not be supported by all browser.
*
*/
if ( location.hash ){
/*
* forEach can be uitlized here, but this provide better cross platform
* compatibitliy.
*
*/
let temp = location.hash.substr(1).split("&");
for ( let i = 0; i < temp.length; i++ ){
let param = temp[i].split("=");
// if param[0] is 0 length that is an invalid look something like &=abc.
if ( param[0].length === 0 ) continue;
/*
* if more than > 2 that is also invalid but just grab the first one anyway.
* if exactly 1 that is something like &filter=&somethingelse. So that is an
* empty param.
*
*/
let value = param.length > 1? param[1] : '';
// This does not check if a url receive the same parameter multiple times.
hashes[param[0]] = value;
}
}
/*
* If there is a quicksearch value assign that to the hashes object.
* If not delete quicksearch name from the hashes object if there is.
* With this way, if there was a value for quicksearch in the hash
* object, it will just get overwritten. If not that index will be create.
* The delete statement is just for cosmetic. This we turn the url back
* to without hashes if there isn't a value.
* However, for faster code, this can simply be done as
*
* hashes[quicksearchParamName] = $("#quicksearch").val()
*
* If do like the above, whether if there is a value or not, the hash
* parameter for quicksearch will always be built.
*
*/
if ( whocall === 1 ){
// 1 : quicksearch
if ( $("#quicksearch").val() ) hashes[quicksearchParamName] = encodeURIComponent($("#quicksearch").val());
else delete hashes[quicksearchParamName];
qsRegex = new RegExp($("#quicksearch").val(), "gi");
/*
* For lastState, if setup correctly, val will give an empty string
* or something here.
*
*/
lastState["searchFilter"] = $("#quicksearch").val();
} else if ( whocall === 2 ){
// 2 : filter
/*
* If done correctly there will always be a filter value when the user
* choose an option
*
*/
hashes[filterParamName] = encodeURIComponent(filterValue);
lastState["filterValue"] = filterValue;
} else {
// 3 : price sort
/*
* If from user selecting, without an option for resetting. If done
* correctly, there will always be a sortValue and sortType.
*
*/
lastState["sortValue"] = sortValue = obj.value;
lastState["sortType"] = obj.selectedOptions[0].getAttribute('data-sorttype');
hashes[sortValueParamName] = encodeURIComponent(obj.value);
hashes[sortTypeParamName] = obj.selectedOptions[0].getAttribute('data-sorttype');;
sortAscending = hashes[sortTypeParamName] === "asc"? true : false;
}
// Update the grid.
$grid.isotope({ sortBy: sortValue , sortAscending: sortAscending});
/*
* Update the hash without making filterWithHash() update the grid.
* Join everything in hashes together into a string. Always append &
* after a key. But when assign to "location.hash", remove the last
* character(extra &) from the string.
*
*/
for ( const k in hashes ) hashStr += k + "=" + hashes[k] + "&";
gridAlreadyUpdated = true;
location.hash = hashStr.substr(0, hashStr.length - 1);
}
/*
* This function below can be customize to utilize not just only hashes
* but also "Get Requests"
*
*/
function filterWithHash() {
// If the grid is already updated, there is nothing to do.
if ( gridAlreadyUpdated ) {
gridAlreadyUpdated = false;
return;
}
var hashFilter = getHashFilter();
var searchFilter = getSearchFilter();
var sortParam = getSortParam();
/*
* If the last time we access the value for the filters and it
* is the same at this time. There isn't a point to re-execute the code
*/
if ( $grid && lastState["searchFilter"] === searchFilter
&& lastState["filterValue"] === hashFilter
&& lastState["sortValue"] === sortParam[0]
&& lastState["sortType"] === sortParam[1] ) {
return;
}
lastState["sortValue"] = sortParam[0];
lastState["sortType"] = sortParam[1];
lastState["searchFilter"] = searchFilter;
lastState["filterValue"] = hashFilter;
/*
* If searhFilter is there, utilize it.
* Else, qsRegex is reset. That is because the user could input a value into the
* search field and then later delete that value then press enter. If that happe