基于JQuery的一句代码实现表格的简单筛选


效果图:

代码:
复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryTableFilter.aspx.cs" Inherits="JqueryTableFilter" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Script/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#Text1").keyup(function() {
var filterText = $(this).val();
$("#<%=GridView1.ClientID %> tr").not(":first").hide().filter(":contains('" + filterText + "')").show();;
}).keyup();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:60%;">
<input id="Text1" type="text" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="OrderID" DataSourceID="SqlDataSource1"
HorizontalAlign="Left" PageSize="50" >
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID" ReadOnly="True"
SortExpression="OrderID" InsertVisible="False" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
SortExpression="CustomerID" />
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"
SortExpression="EmployeeID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate"
SortExpression="OrderDate" />
<asp:BoundField DataField="RequiredDate" HeaderText="RequiredDate"
SortExpression="RequiredDate" />
<asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate"
SortExpression="ShippedDate" />
<asp:BoundField DataField="ShipVia" HeaderText="ShipVia"
SortExpression="ShipVia" />
<asp:BoundField DataField="Freight" HeaderText="Freight"
SortExpression="Freight" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT top 50 * FROM [Orders]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>

JQuery代码就:
复制代码 代码如下:

$(function() {
$("#Text1").keyup(function() {
var filterText = $(this).val();
$("#<%=GridView1.ClientID %> tr").not(":first").hide().filter(":contains('" + filterText + "')").show();;
}).keyup();
});


里面最重要的就是JQuery的选择器:

1:$("#<%=GridView1.ClientID %> tr")选择表格的所有行;
2:not(":first"):除去第一行表头行;
3:filter(":contains('" + filterText + "')"):从上面所选择的行里面筛选出行文本中包含filterText 的行显示出来;
4:最后加一句keyup()是为了在提交后重新触发keyup事件。(但是在这里没有作用因为我用的客户端控件没有ViewState
若是服务器端控件就会看见他的作用)。

JQuery的选择器的强大之处,让我们能救这么简单的实现客户端的简单筛选。最后加一句关于表格筛选有JQuery插件提供
给我们选择, 但是这种简单的功能,我不会去选择加入一个JavaScript文件库,呵呵。
作者:破 浪
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3