繁体   English   中英

部分匹配数据属性

[英]Partial Matches data attribute

我正在使用与itemsselectors数据属性product-collection__category完全匹配的类别过滤 selectors 但是我只希望它是部分匹配或惰性匹配。 例如,如果selector包含“猫”,它仍然会包含items有“猫”,“类别”等我都试过if (categories[i] *= cat)但它是错误的。

小提琴

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>

$(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();
            }
        });
    });
});

我简化了小提琴,以便您可以看到选择器并进行测试-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/是这里的区别,它允许测试类别的真实性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM