如何无需按回车键即可在搜索框实时筛选PHP渲染的JSON数据表格
问题排查与修复方案
核心问题列表
- 表格ID大小写不匹配:JS代码中通过
getElementById("myTable")获取表格,但是PHP输出的表格ID是MyTable(首字母大写),DOM选择器区分大小写,导致无法获取到表格对象,筛选逻辑直接失效 - 表格单元格标签未闭合:PHP循环输出数据行时,每个单元格结束只写了
<td>,没有写闭合标签</td>,导致DOM结构异常,无法正常获取单元格内容 - 筛选范围限制:当前筛选逻辑只匹配每行的第6个单元格(索引为5的td,对应name字段),如果需要全字段匹配需要调整逻辑
- 多余空列冗余:表头和数据行中都插入了大量空的
<th><pre></pre></th>、<td>,既浪费渲染资源也会导致单元格索引计算错误
修复后的完整代码
前端HTML+CSS部分
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> *{ box-sizing: border-box; } #myInput { background-image: url('/css/searchicon.png'); background-position: 10px 10px; background-repeat: no-repeat; width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } #myTable { border-collapse: collapse; width: 100%; border: 1px solid #ddd; font-size: 18px; } #myTable th, #myTable td { text-align: left; padding: 12px; } #myTable tr { border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { background-color: #f1f1f1; } </style> </head> <body> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索.." title="输入关键词搜索">
PHP后端生成表格部分
<?php // 表格ID统一为小写myTable,和JS选择器保持一致 echo "<table id='myTable'>"; echo "<tr class='header'>"; echo "<th>Id</th>"; echo "<th>Bin</th>"; echo "<th>Tür</th>"; echo "<th>Banka Adı</th>"; echo "<th>Type</th>"; echo "<th>Name</th>"; echo "<th>Oluşturma Tarihi</th>"; echo "<th>Güncelleme Tarihi</th>"; echo "</tr>"; $json_url = "你的实际JSON接口地址"; $json = file_get_contents($json_url); $data = json_decode($json, TRUE); foreach($data as $record) { echo "<tr>"; // 所有单元格补充闭合标签</td> echo "<td>".$record["id"]."</td>"; echo "<td>".$record["bin"]."</td>"; echo "<td>".$record["tur"]."</td>"; echo "<td>".$record["banka_adi"]."</td>"; echo "<td>".$record["type"]."</td>"; echo "<td>".$record["name"]."</td>"; echo "<td>".$record["created_at"]."</td>"; echo "<td>".$record["updated_at"]."</td>"; echo "</tr>"; } echo "</table>"; ?>
优化后的筛选JS代码(支持全字段匹配)
<script> function myFunction() { var input, filter, table, tr, td, i, j, txtValue, match; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // 遍历所有数据行,跳过表头 for (i = 1; i < tr.length; i++) { tr[i].style.display = "none"; td = tr[i].getElementsByTagName("td"); match = false; // 遍历当前行所有单元格匹配关键词 for(j = 0; j < td.length; j++){ txtValue = td[j].textContent || td[j].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { match = true; break; } } if(match){ tr[i].style.display = ""; } } } </script> </body> </html>
内容的提问来源于stack exchange,提问作者mill
相关产品推荐
相关产品推荐

