JavaScript案例—页面搜索

今天给大家分享一篇关于前端页面搜索的案例,有了这个案例,在表格数据中可以进行快速查找,比在浏览器中使用ctrl+F体验比较好。

效果图:

这里写图片描述

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>页面搜索实例</title>
    <script src="jquery.js"></script>
    <style>
        table{
            width:400px;
            border:1px solid blue;
            border-collapse: collapse;
        }
        table th{
            height:30px;
            border:1px solid blue;
            text-align: center;
        }
        table td{
            height:30px;
            border:1px solid blue;
            text-align: center;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <th>姓名</th>
            <th>性别</th>
            <th>电话</th>
        </tr>
        <tr>
            <td>张三</td>
            <td></td>
            <td>13111112222</td>
        </tr>
        <tr>
            <td>李四</td>
            <td></td>
            <td>13233334444</td>
        </tr>
        <tr>
            <td>移动充值</td>
            <td></td>
            <td>10086</td>
        </tr>
        <tr>
            <td>联通充值</td>
            <td></td>
            <td>10010</td>
        </tr>
    </table>
    <div style="100%;height:20px"></div>
    <div>
        <input type="text" name="" id="">
        <input type="button" value="搜索">
    </div>
</body>
<script>
    $('input[type=button]').click(function(){
        var text = $('input[type=text]').val();
        $('table tr').not(':first').hide().filter(':contains("'+text+'")').show();
    });
</script>
</html>

代码比较简单,首先给button按钮添加单击事件,然后获取文本框中的内容,再从表格中tr进行查找,首先把表头的tr过滤掉,然后把其他的tr全部隐藏掉,然后按照内容进行过滤,把过滤出来的行显示出来。

原文地址:https://www.cnblogs.com/cnsec/p/13407047.html