[英]Partial Matches data attribute
I'm using this category filter that exactly matches data attribute product-collection__category
of the items
and the selectors
. 我正在使用与items
和selectors
数据属性product-collection__category
完全匹配的类别过滤 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. 例如,如果selector
包含“猫”,它仍然会包含items
有“猫”,“类别”等我都试过if (categories[i] *= cat)
但它是错误的。
HTML 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/ 我简化了小提琴,以便您可以看到选择器并进行测试-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. http://api.jquery.com/is/是这里的区别,它允许测试类别的真实性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.