使用jQuery实现基于输入框与<p class="name">的Div过滤功能
Solution: Filter Divs by
.name Content on Input Hey there! I've put together a simple, working implementation that does exactly what you need—shows all divs by default, then filters them in real-time as the user types in the input box based on the text inside <p class="name"></p>. Let's break this down step by step:
1. HTML Structure
First, set up your input field and a container to hold all your filterable divs:
<!-- Search Input --> <input type="text" id="searchInput" placeholder="Type to filter items..."> <!-- Container for Filterable Divs --> <div id="itemsContainer"> <div class="item"> <p class="name">Apple Pie</p> <p>Classic dessert with fresh apples</p> </div> <div class="item"> <p class="name">Chocolate Cake</p> <p>Rich, fudgy chocolate treat</p> </div> <div class="item"> <p class="name">Lemon Tart</p> <p>Tart and creamy lemon filling</p> </div> <div class="item"> <p class="name">Vanilla Ice Cream</p> <p>Smooth and creamy vanilla flavor</p> </div> </div>
2. Basic CSS (Optional but Polished)
Add some simple styling to make the interface look clean:
#searchInput { padding: 10px; width: 350px; border: 1px solid #ddd; border-radius: 4px; margin: 20px 0; } .item { padding: 15px; border: 1px solid #eee; border-radius: 4px; margin-bottom: 10px; transition: all 0.3s ease; /* Smooth hide/show transition */ }
3. JavaScript Filter Logic
This is where the filtering happens. We'll listen for input changes, then check each div's .name content against the user's input:
// Grab our core elements const searchInput = document.getElementById('searchInput'); const itemDivs = document.querySelectorAll('#itemsContainer .item'); // Listen for input events (triggers as the user types) searchInput.addEventListener('input', function() { // Normalize input to lowercase for case-insensitive search const searchTerm = this.value.trim().toLowerCase(); // Loop through each item div to check for matches itemDivs.forEach(div => { // Get the text from the .name paragraph, normalize to lowercase const itemName = div.querySelector('.name').textContent.toLowerCase(); // Show the div if it matches, hide it if not div.style.display = itemName.includes(searchTerm) ? 'block' : 'none'; }); });
Bonus Tips to Enhance Functionality
- Case Sensitivity: If you want exact case matching, just remove the
.toLowerCase()calls from both the search term and item name. - Debouncing: If you have hundreds of divs, add a debounce function to delay the filter logic until the user stops typing (reduces unnecessary re-renders).
- Exact Match: Replace
includes()with===if you only want to show items that perfectly match the search term. - Empty Input Reset: The code already shows all divs when the input is empty—no extra work needed here!
内容的提问来源于stack exchange,提问作者Gue Alex
相关产品推荐
相关产品推荐

