使用jQuery检测空Div并隐藏无内容区域的技术求助
Fixing Empty Region Display After Filtering with jQuery
Hey Michelle, let's sort out that annoying issue where empty regions stick around after using the filter! Here's a practical solution that'll automatically hide any region with no visible producers once filtering is done:
Step 1: Target Your HTML Structure First
First, make sure you’re using the right selectors for your page’s setup. Let’s assume your code follows this pattern (adjust selectors to match your actual HTML):
- Each region is wrapped in a container with a class like
region-container - Each producer’s collapsible div has a class like
producer-collapse
Step 2: Add the jQuery Logic
Drop this code into your script (just confirm jQuery is already loaded on your page first!):
$(document).ready(function() { // Reusable function to check and hide empty regions function hideEmptyRegions() { // Reset: Show all regions first to clear previous filter state $('.region-container').show(); // Loop through every region container $('.region-container').each(function() { // Count how many visible producers are inside this region const visibleProducers = $(this).find('.producer-collapse:visible').length; // Toggle visibility: Show if there are producers, hide if empty $(this).toggle(visibleProducers > 0); }); } // Trigger the function when your filter is used // Example 1: For a filter button click $('#filter-button').on('click', function() { // Run your existing filter logic here first... hideEmptyRegions(); // Then clean up empty regions }); // Example 2: For real-time input filtering (like typing in a search box) $('#filter-input').on('input', function() { // Run your existing real-time filter logic here first... hideEmptyRegions(); // Then clean up empty regions }); });
Quick Adjustments for Your Exact Code:
- Replace
.region-containerwith the actual selector for your region wrappers (could be a class, ID, or even a<section>element) - Replace
.producer-collapsewith the selector for your individual producer collapsible divs - If your filter has a callback (like after animation finishes), move
hideEmptyRegions()into that callback to ensure it runs after filtering is fully complete
The toggle() method here is a clean shortcut—it shows the region if there are visible producers, and hides it if the region is empty, no messy if/else blocks needed!
内容的提问来源于stack exchange,提问作者Michelle Britton
相关产品推荐
相关产品推荐

