jQuery Siblings选择器异常,求助实现页面实时区分大小写搜索过滤
Hey there! Let's work through your real-time search and filtering problems together—you've got two main hurdles here: making :contains case-sensitive, and fixing the siblings() method not behaving as expected. Let's break this down step by step.
1. Fixing Case-Sensitive Text Filtering
First off, jQuery's built-in :contains selector is case-insensitive by default, which isn't what you want. The solution is to create a custom case-sensitive version of the selector. Here's how to do that:
// Add a custom case-sensitive contains selector $.expr[':'].containsCase = function(obj, index, meta) { // Use native indexOf (which is case-sensitive) to check for the search term return $(obj).text().trim().indexOf(meta[3].trim()) !== -1; };
This selector checks if an element's text includes your search value with strict case matching, and we add .trim() to avoid issues with accidental leading/trailing spaces in the input or element text.
2. Fixing the siblings() Issue
The problem with using siblings() here is that it only targets elements that share the exact same parent as the matched element. If your .col-3 elements are spread across different parent containers, siblings() won't catch all non-matching elements. Even if they are siblings, selecting one matched element and hiding its siblings would accidentally hide other matched elements too.
A better approach is to:
- Reset all
.col-3elements first (show them and reset styles) - Find all matched elements
- Highlight the matches
- Hide everything that doesn't match
Here's the complete working code:
$(document).ready(function(){ // Custom case-sensitive contains selector $.expr[':'].containsCase = function(obj, index, meta) { return $(obj).text().trim().indexOf(meta[3].trim()) !== -1; }; $(':text').on('change paste keyup', function(){ var searchVal = $(this).val().trim(); // Reset all .col-3 elements: show them and reset styles $('.col-3').css({'background':'#fff','color':'#000'}).show(); if(searchVal !== ''){ // Get all elements that match the case-sensitive search var matched = $('.col-3:containsCase(' + searchVal + ')'); // Highlight the matched elements matched.css({'background':'#ffeb3b','color':'#333'}); // Hide all elements that don't match $('.col-3').not(matched).hide(); } }); });
Quick Notes
- Using
.trim()on both the input value and element text prevents false negatives from extra spaces. - The
.not(matched)method is more reliable thansiblings()because it targets all non-matching.col-3elements across the page, regardless of their parent structure. - We reset the elements every time the input changes to ensure the UI stays consistent as the user types.
内容的提问来源于stack exchange,提问作者Ehsan Ali

