如何在JavaScript表格过滤器中实现精确匹配?
实现表格数字的精确匹配过滤
当前你的表格过滤逻辑使用indexOf()做包含匹配,导致输入"1"时会显示所有含"1"的条目(比如1、11、14)。要实现精确匹配,只需修改判断条件为严格相等即可,以下是调整后的完整代码:
<!DOCTYPE html> <html> <title>Dublin Transport History</title> <meta content="width=device-width, initial-scale=1" name="viewport"> <link href="w3.css" rel="stylesheet"> <link href="default.css" rel="stylesheet"> <body> <div class="w3-container"> <h2>Title</h2> <input id="myInput" onkeyup="myFunction()" placeholder="Search Number..." title="Type in a Number" type="text"> <table id="myTable"> <tr class="header"> <th class="w3-center">A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th class="w3-center">F</th> </tr><tr> <td class="w3-center">1</td> <td>John</td> <td>Smith</td> <td>Green</td> <td>Boat</td> <td class="w3-center">House</td> </tr><tr> <td class="w3-center">11</td> <td>Adam</td> <td>Smith</td> <td>Pink</td> <td>Car</td> <td class="w3-center">Apartment</td> </tr><tr> <td class="w3-center">14</td> <td>Nelson</td> <td>Tower</td> <td>Red</td> <td>Bicycle</td> <td class="w3-center">Cottage</td> </tr> </table> </div> <script> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.trim().toUpperCase(); // 去除首尾空格,统一格式 table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent.trim().toUpperCase(); // 清除单元格内容的冗余空格 // 替换原包含匹配为严格相等匹配 if (txtValue === filter) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> </body> </html>
关键改动说明:
- 添加
trim():去除输入框和单元格内容的首尾空格,避免因空格导致的匹配失败(比如单元格内容是" 1 "时也能匹配输入的"1")。 - 替换匹配逻辑:把
txtValue.toUpperCase().indexOf(filter) > -1改成txtValue === filter,从"包含匹配"切换为"完全相等匹配"。
如果表格第一列都是纯数字,也可以用数字类型比较,避免字符串格式问题,修改判断部分为:
// 转成整数进行精确匹配 if (parseInt(txtValue, 10) === parseInt(filter, 10)) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; }
内容的提问来源于stack exchange,提问作者Dar
相关产品推荐
相关产品推荐

