文本输入为空或仅含空格时,如何移除搜索筛选的高亮类?
问题描述
我有一个可正常运行的搜索筛选器,输入文本时会高亮匹配的列表项。但遇到的问题是,清空文本输入框后,列表中的所有项都被添加上了高亮类。请问当文本输入为空或仅含空格时,该如何移除所有高亮类?我并非JS/jQuery资深开发者,尝试实现输入为空时移除类的操作未成功。
当前使用的JS代码:
const $input = $("#tagfilter"); const $items = $(".taglist"); function filterItems(text) { text = text.trim().toLowerCase(); $items.each(function() { const cont = $.trim($(this).text().toLowerCase()); const hasText = cont.includes(text); $(this).toggleClass("fw-bold text-light bg-dark rounded p-1", hasText) }); } $input.on("input", function() { filterItems($(this).val()); });
对应的HTML结构:
<input id="tagfilter" class="form-control" type="text" autocomplete="off"> <div class="taglist">item one</div> <div class="taglist">item two</div> <div class="taglist">item three</div>
解决方案
问题根源:当输入内容经过trim()后为空字符串时,cont.includes(text)会返回true——因为任何字符串都默认包含空字符串,导致所有列表项都被加上了高亮类。
修改后的代码如下:
const $input = $("#tagfilter"); const $items = $(".taglist"); // 将高亮样式类统一存为变量,便于维护 const highlightClasses = "fw-bold text-light bg-dark rounded p-1"; function filterItems(text) { text = text.trim().toLowerCase(); // 若处理后文本为空,直接移除所有项的高亮类 if (!text) { $items.removeClass(highlightClasses); return; } // 有有效输入时,执行原匹配逻辑 $items.each(function() { const cont = $.trim($(this).text().toLowerCase()); const hasText = cont.includes(text); $(this).toggleClass(highlightClasses, hasText) }); } $input.on("input", function() { filterItems($(this).val()); });
关键修改点
- 把重复的高亮样式类定义为变量
highlightClasses,减少冗余代码,后续修改样式更方便。 - 在
filterItems函数开头增加判断:如果处理后的输入文本为空,直接调用removeClass移除所有列表项的高亮类,然后终止函数执行。 - 只有当输入有有效内容时,才执行原有的匹配和高亮逻辑。
这样修改后,清空输入框或输入全空格时,所有列表项的高亮样式会被移除,符合预期效果。
内容的提问来源于stack exchange,提问作者Scot's Scripts
相关产品推荐
相关产品推荐

