0

I have a list of elements. Upon clicking a link, I want to filter the elements by a class. (so far it's okay). The trouble: if there are no elements with that class, I want to print a message saying that.

$('.filterEventsLinks a').click(function(){
     // count total number of events
     var evCount = $('.singleEvent').length;

     // a list of comma-separated class names to filter are stored in the data attribute of the fired element
     // for example: <a data-category="kids,teens,adults" href="#"></a>
     var cats = $(this).data('category');

     // split into an array
     var catArr = cats.split(',');

    // loop through
    for(var i in catArr) {
        var cat = '.CAT-' + catArr[i];

        // hide things that do not have this category
        $('.singleEvent').not(cat).slideUp(200);
        // show things that do
        $(cat).slideDown(200);

    }

    // count number of remaining visible elements
    var evCount = $('.singleEvent').filter(':visible').length;

    // do more...
});

Everything here works as expected except that last line. The last line that doesn't seem to work. It always returns the number of elements that exist, not the number that are currently visible.

Same problem listed in this SO question: Count number of elements in list after slideup/slidedown

4

3 回答 3

3

Instead of looping through the categories in the data-attribute, you can build a selector to match them all at once:

$('.filterEventsLinks a').click(function(){    
     var cats = $(this).data('category');
     //create a selector to match the categories
     var selector = '.CAT-' + cats.split(',').join(',.CAT-');

     //get filtered elements
     var $elems = $(selector);
     // hide things that do not have this category
     $('.singleEvent').not($elems).slideUp(200);
     // show things that do
     $elems.slideDown(200);

     // count number of remaining visible elements
     var evCount = $elems.length;
});
于 2013-09-10T18:39:41.107 回答
2

You'll have to count the elements after the animation has completed. When the elements are animating they are still visible, or you could just keep the elements in a collection and count that :

$('.filterEventsLinks a').click(function(){
     var evCount = $('.singleEvent').length,
         cats    = $(this).data('category').split(','),
         elems   = $([]);

     $.each(cats, function(_, cat) {
        var _cat = $('.CAT-' + cat);
        $('.singleEvent').not(_cat).slideUp(200);
        _cat.slideDown(200);
        elems = elems.add(_cat);
    }

    // you're sliding all .singleEvent elements except "elems" up, so just count
    // the elements in "elems" instead, as that should be the visible ones
    var evCount = elems.length;
});
于 2013-09-10T18:30:10.190 回答
0

Instead of counting the currently visible elements, I just used the same criteria as used earlier, and counted those, i.e.:

$(cat).length;

Which was a much simpler way around this whole thing.

于 2013-09-10T19:04:45.283 回答