现在的位置: 首页 > 综合 > 正文

用一句jQuery代码实现表格的简单筛选

2012年08月12日 ⁄ 综合 ⁄ 共 2169字 ⁄ 字号 评论关闭

    今天看到破狼的用一句JQuery代码实现表格的简单筛选,感觉此功能很好用,学习了。    

代码

 1 <head runat="server">
 2     <title>jQuery筛选数据</title>
 3     <link rel="Shortcut Icon" href="Images/favicon.ico" />    
 4     <script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
 5     <script type="text/javascript">
 6         $(function(){
 7             $("#Text1").keyup(function(){
 8                 var filterText=$(this).val();
 9                 $("#<%=GridView1.ClientID %> tr").not(":first").hide()
10                     .filter(":contains('"+filterText+"')").show();;
11             }).keyup();
12         });
13     </script>
14 </head>
15 <body>
16     <form id="form1" runat="server">
17     <div style="width: 60%">
18         关键字:<input id="Text1" type="text" />
19         <asp:GridView ID="GridView1" runat="server" AllowPaging="True" Width="100%" 
20          PageSize="50" HorizontalAlign="Left" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
21             <Columns>
22                 <asp:TemplateField HeaderText="编号">
23                     <ItemTemplate>
24                         <%# Container.DataItemIndex+1 %><!--行号-->
25                     </ItemTemplate>
26                 </asp:TemplateField>
27                 <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
28                 <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
29                 <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
30                 <asp:BoundField DataField="ParentId" HeaderText="ParentId" SortExpression="ParentId" />
31             </Columns>
32         </asp:GridView>
33         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:IMONEYConnectionString %>"
34             SelectCommand="SELECT * FROM [IMoneyClass]"></asp:SqlDataSource>
35     </div>
36     </form>
37 </body>

 

里面最重要的就是JQuery的选择器(摘自原文):

1:$("#<%=GridView1.ClientID %> tr")选择表格的所有行;

2:not(":first"):除去第一行表头行;

3:filter(":contains('" + filterText + "')"):从上面所选择的行里面筛选出行文本中包含filterText 的行显示出来;

4:最后加一句keyup()是为了在提交后重新触发keyup事件。(但是在这里没有作用因为我用的客户端控件没有ViewState

    若是服务器端控件就会看见他的作用)。

 

抱歉!评论已关闭.