jQuery实现前端表格数据快速搜索功能

作者:开源拾贝时间:2026-10-23 09:32:28浏览:165

本文介绍一种基于jQuery的前端页面搜索功能实现方案。通过绑定按钮点击事件,获取输入框内容,利用jQuery选择器遍历表格行,隐藏表头并过滤显示匹配内容的行。该方法比浏览器原生查找体验更佳,适合在数据表格中实现快速定位功能。

jQuery前端表格搜索功能实现

本文分享一个JavaScript前端页面搜索功能的实例,供读者参考学习。

该案例展示了如何在网页表格中实现快速查找功能,其交互体验优于浏览器自带的Ctrl+F搜索。

具体运行效果如下所示。

jQuery前端表格搜索功能实现

实现代码如下:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>页面搜索实例</title>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.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="width: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>

代码逻辑较为简单:首先为按钮绑定单击事件,接着获取文本框内的输入值。随后遍历表格中的所有行(tr),首先排除表头行,将剩余所有行隐藏,最后根据输入内容进行过滤,仅显示包含该内容的行。

感兴趣的用户可以通过在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码的运行效果。

此外,本站还提供其他几款具备前端页面搜索功能且功能更强大的在线工具:

php在线函数参考表: http://tools.jb51.net/table/php_fun_table

全国少数民族分布在线查询工具: http://tools.jb51.net/bianmin/minzufenbu

世界节日在线查询工具: http://tools.jb51.net/bianmin/jieri

世界各国区号代码及时差查询表: http://tools.jb51.net/bianmin/shicha

世界各国/地区货币查询表: http://tools.jb51.net/bianmin/huobi

世界各国首都查询表: http://tools.jb51.net/bianmin/shoudu

更多关于jQuery的相关内容,可查看本站专题:《jQuery页面元素操作技巧汇总》、《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery扩展技巧总结》及《jquery选择器用法总结》。

希望本文所述的jQuery程序设计内容能对大家有所帮助。

作者最新文章