部分匹配数据属性

时间:2014-05-02 12:37:11

标签: javascript jquery regex

我使用的此类别filterproduct-collection__categoryitems的数据属性selectors完全匹配。但我希望它只是部分或懒惰的匹配。例如,如果selector包含"猫",它仍将包含items,其中包含" cat",#34;类别"等我试过if (categories[i] *= cat)但是错了。

Fiddle

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

1 个答案:

答案 0 :(得分:1)

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

相关问题