$.each(mappings, function(key, item) {
        if (match(selected_values, item)) {
          $(key).show("slow");
        } else {
          $(key).hide("slow");
        }
    });

    //At this point, all items are still visible!
    var item_count = $('.item').filter(':visible').length;
    if (item_count < 12) { 
        $('.item').not(':visible').slice(0,12 - item_count).show();
    }

I am iterating over a data structure, and depending on some selected attributes, some items are hidden, other shown.

Trouble is, the client requests a minimum items visible. So even if the filtering works correctly, and I get a number of 3 visible items, they should be padded up with 9 more elements, so that at least always 12 are shown.

Now, after the each iteration, it appears that the .show() and .hide() functions don't have terminated yet. How and where can I apply the padding functions correctly?

I've checked Invoking a jQuery function after .each() has completed but his applies the function after each .show() or .hide(), which is not what I want (it's not ok to pad up during iteration, we first need to hide all which do not apply).

This one: execute callback after jquery each iteration doesn't work, when the function is called I have the same problem (show() and hide() haven't completed).

EDIT: I just found out that removing the "slow" attribute in the .show() and .hide() methods solves the problem. Now, what if I'd like to keep the animations?

有帮助吗?

解决方案

It's synchronous, so you shouldn't need a callback, but you have asynchronous animations, and that's the real issue. Just use a counter in the loop instead of checking the elements length, or add a class :

$.each(mappings, function(key, item) {
    if (match(selected_values, item)) {
      $(key).addClass('selected').show("slow");
    } else {
      $(key).hide("slow");
    }
});

if ($('.item.selected').length < 12) { 
    $('.item').not('.selected').slice(0,12 - item_count).show();
}

其他提示

You might get good results by just adding .stop() to the chain:

$('.item').not(':visible').slice(0,12 - item_count).stop().show();

Any previously initiated animation (show/hide) will be halted, and the item will just be shown.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top