如何修改JS过滤逻辑实现郊区列表仅按首字母匹配筛选
解决方案
问题根因
你的两种开头匹配写法本身逻辑没有问题,不生效的核心原因有两个:
- PHP引入
suburbs.php输出郊区列表时,<li>标签内的文本大概率带有前置的缩进、换行、空格等空白字符,导致实际读取到的文本开头不是郊区名称,匹配失败 - 你把
<input>直接放在<ul>标签内部不符合HTML规范,部分浏览器会自动生成<li>包裹这个输入框,导致你获取到的li列表存在多余的无效项
修改步骤
1. 先修正HTML结构(可选但强烈建议)
把输入框移到ul外部,避免DOM结构异常:
<input type="text" placeholder="Search..." id="myInput" onkeyup="filterFunction()" style="padding: 10px; background-color:#343434; border: 0px; color: white;"> <ul class="nav nav-pills" id="mainNav"> <?php include_once( 'suburbs.php' );?> </ul>
2. 修改JS筛选逻辑
提取文本时先去除首尾空白,再判断是否以搜索内容开头:
function filterFunction() { var input, filter, div, a, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); div = document.getElementById("mainNav"); a = div.getElementsByTagName("li"); for (i = 0; i < a.length; i++) { txtValue = a[i].textContent || a[i].innerText; // 去除首尾空白后转大写,再判断是否以搜索内容开头 if (txtValue.trim().toUpperCase().startsWith(filter)) { a[i].style.display = ""; } else { a[i].style.display = "none"; } } }
如果需要兼容IE等老旧浏览器,可以把startsWith替换为indexOf(filter) === 0:
if (txtValue.trim().toUpperCase().indexOf(filter) === 0) {
内容的提问来源于stack exchange,提问作者Mark Pearce
相关产品推荐
相关产品推荐

