如何在data-search属性中实现无重音模糊搜索?
解决方案
你的核心问题是当前代码在匹配元素的显示文本,但你实际需要匹配的是data-search属性值,同时没对搜索词和目标值做标准化处理(比如统一大小写、去除重音),导致搜A-plus这类关键词匹配不到。下面是修改后的代码,能实现你要的效果:
修改后的JavaScript代码
// 标准化字符串:去除重音、转小写、清理特殊字符 function normalizeStr(str) { return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "") // 移除重音符号 .toLowerCase() // 统一转成小写 .replace(/#/g, ""); // 去掉多余的#号 } function findElementByText(elem, text) { const normalizedSearch = normalizeStr(text); // 遍历目标元素,基于data-search属性做匹配 return $(elem).filter(function() { const dataSearchVal = $(this).attr("data-search") || ""; const normalizedData = normalizeStr(dataSearchVal); // 检查标准化后的搜索词是否是data-search值的子串 return normalizedData.includes(normalizedSearch); }).clone().get(); } $(".searcher").on('keyup change',function(){ $(".result").html(''); const value = $(this).val().trim(); const listItems = ".items"; const found = findElementByText(listItems, value); if(found.length > 0) { $(".result").html(found); } else { $(".result").html('<i>Not found!</i>'); } });
对应HTML代码(无需改动)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!--search:--> <input class="searcher"> <ul> <!--items:--> <li class="items" data-search="A-plus">#À plus !</li> </ul> <!--result:--> result:<br> <div class="result"></div>
关键改动说明
- 新增
normalizeStr函数:把字符串转成无重音、全小写的标准化格式,解决重音和大小写不匹配的问题,比如将À转为a、Plus转为plus。 - 放弃
:contains选择器,改用filter遍历元素,直接读取data-search属性值进行匹配,完全贴合你的需求。 - 匹配逻辑改为检查标准化后的搜索词是否包含在标准化后的
data-search值中,这样搜A、Plus、A-plus都能命中目标元素。
内容的提问来源于stack exchange,提问作者ramin
相关产品推荐
相关产品推荐

