在jQuery each函数中实现AND逻辑以完成多条件筛选功能
Got it, let's resolve the issue where your filter is using OR logic instead of the desired AND logic. The core problem is in how your applyFilter() function checks for matching filters—right now it shows an item if it matches any active filter, but we need to adjust it to only show items that match all active filters.
The Problem with the Original Code
In your current applyFilter() function, you loop through the item's classes and show it as soon as you find one that matches any active filter. This creates the OR behavior you're seeing:
for ( i = 0; i < classes.length; i++ ) { if ( filtersActive.indexOf( classes[ i ] ) > -1 ) { $( this ).addClass( 'show-workItem' ); } }
Modified applyFilter() Function (AND Logic)
Replace your existing applyFilter() with this updated version, which checks that the item has all active filters in its class list:
function applyFilter () { // Go through all portfolio items and hide/show as necessary $works.each( function () { var $item = $( this ); // Start by hiding the item $item.removeClass( 'show-workItem' ); if ( cFilter.hasClass( 'showAll' ) || filtersActive.length === 0 ) { // Show all items if showAll is active or no filters are selected $item.addClass( 'show-workItem' ); } else { // Track if the item matches ALL active filters var matchesAllFilters = true; // Check each active filter against the item's classes for ( var i = 0; i < filtersActive.length; i++ ) { var activeFilter = filtersActive[ i ]; // If the item doesn't have this filter class, mark as non-matching if ( !$item.hasClass( activeFilter ) ) { matchesAllFilters = false; break; // No need to check further filters } } // Only show the item if it matches every active filter if ( matchesAllFilters ) { $item.addClass( 'show-workItem' ); } } } ); }
Key Changes Explained
- Default Hide: We start by hiding every item, so only those that meet all criteria get shown.
- All Filters Check: We use a boolean flag (
matchesAllFilters) to track if the item passes every filter check. - Early Exit: As soon as we find a filter the item doesn't have, we set the flag to
falseand break out of the loop—no need to waste time checking other filters. - Show Only Valid Items: If the item passes all filter checks, we add the
show-workItemclass to display it.
How It Works for Your Scenario
When a user selects "单层住宅", "3卧室", and "2浴室":
- The
filtersActivearray will contain all three filter values. - For each product, the function checks if it has all three classes in its class list.
- Only products that have all three classes will be marked to show—exactly the AND logic you need.
内容的提问来源于stack exchange,提问作者Miraj Aryal

