本章节我们将学习如何使用 JS/CSS 实现表格搜索或过滤功能。
先看下效果如下:
- <input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索..">
-
- <table id="myTable">
- <tr class="header">
- <th style="width:60%;">Name</th>
- <th style="width:40%;">Url</th>
- </tr>
- <tr>
- <td>Google</td>
- <td>www.google.com</td>
- </tr>
- <tr>
- <td>Runoob</td>
- <td>www.cdsy.xyz</td>
- </tr>
- <tr>
- <td>Taobao</td>
- <td>www.taobao.com</td>
- </tr>
- <tr>
- <td>Baidu</td>
- <td>www.baidu.com</td>
- </tr>
- </table>
以下搜索搜索框和联想菜单的样式:
- #myInput {
- background-image: url('/css/searchicon.png'); /* 添加搜索按钮 */
- background-position: 10px 12px; /* 定位搜索按钮 */
- 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;
- }
以下是搜索搜索框和联想菜单的 JavaScript 代码:
- function myFunction() {
- // 声明变量
- var input, filter, table, tr, td, i, txtValue;
- input = document.getElementById("myInput");
- filter = input.value.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 || td.innerText;
- if (txtValue.toUpperCase().indexOf(filter) > -1) {
- tr[i].style.display = "";
- } else {
- tr[i].style.display = "none";
- }
- }
- }
- }
提示:如果要区分大小写的搜索,可以去掉toUpperCase()方法。
提示:如果你要搜索第二列,可以将tr[i].getElementsByTagName('td')[0]中的[0]变为[1]。