I'm using this category filter that exactly matches data attribute product-collection__category
of the items
and the selectors
. But I want it a partial or lazy match only. For example, if the selector
contains "cats", it will still include items
that have "cat","category" etc. I have tried if (categories[i] *= cat)
but it's wrong.
HTML
<div class="product-collection">
<ul>
<li class="product-collection__selector
product-collection__selector--active"
data-product-collection__category="">All</li>
<li class="product-collection__selector"
data-product-collection__category="cat1">Category 1</li>
<li class="product-collection__selector"
data-product-collection__category="cat2">Category 2</li>
</ul>
<ul>
<li class="product-collection__item"
data-product-collection__category="cat1">Item 1 [cat 1]</li>
<li class="product-collection__item"
data-product-collection__category="cat2">Item 2 [cat 2]</li>
<li class="product-collection__item"
data-product-collection__category="cat1 cat2">Item 3 [cat 1, cat 2]</li>
</ul>
</div>
Code
$(function() {
$('.product-collection').each(function() {
var $collection = $(this);
var $selectors = $collection.find('.product-collection__selector,.filterselect__selector');
var $items = $collection.find('.product-collection__item');
$selectors.click(function() {
var $selector = $(this);
var cat = $selector.data('product-collection__category');
$selectors.change(function() {
var $selector = $(this);
var cat = $selector.find('option:selected').data('product-collection__category');
$selectors.removeClass('filterselect__selector--active');
$selector.addClass('filterselect__selector--active'); });
if (cat) {
var containsCategory = function(data) {
var categories = data.split(/\s+/);
for (var i = 0; i < categories.length; i++)
if (categories[i] == cat)
return true;
return false;
};
}
else {
$items.fadeIn();
}
});
});
});
I simplified the fiddle so that you could see the selector and test in action - http://jsfiddle.net/cYFLe/64/
$('li').each(function() {
// test the data attribute for partial
if( $(this).is('[data-product-collection__category*="cat"]') ) {
console.log( $(this).text() );
}
});
http://api.jquery.com/is/ is the difference here, it allows the test of the category for truthiness.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.