JS中table模糊查询
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 </head>
7 <body>
8 <input type="text" name="" id="txt1" value="" />
9 <input type="button" id="btn1" value="搜索" />
10 <table id="tab1" border="" cellspacing="" cellpadding="" width="40%">
11 <thead>
12 <tr>
13 <td>ID</td>
14 <td>姓名</td>
15 <td>年龄</td>
16 </tr>
17 </thead>
18 <tbody>
19 <tr>
20 <td>1</td>
21 <td>张三</td>
22 <td>27</td>
23 </tr>
24 <tr>
25 <td>2</td>
26 <td>李四</td>
27 <td>20</td>
28 </tr>
29 <tr>
30 <td>3</td>
31 <td>张可爱</td>
32 <td>29</td>
33 </tr>
34 <tr>
35 <td>4</td>
36 <td>李XX</td>
37 <td>24</td>
38 </tr>
39 <tr>
40 <td>5</td>
41 <td>马小关</td>
42 <td>35</td>
43 </tr>
44 <tr>
45 <td>6</td>
46 <td>AppleX</td>
47 <td>27</td>
48 </tr>
49 </tbody>
50 </table>
51 </body>
52 <script type="text/javascript">
53 window.onload = function(){
54 var oTab = document.getElementById("tab1");
55 var oTxt = document.getElementById("txt1");
56 var oBtn = document.getElementById("btn1");
57 var oldColor = "";
58
59 changeBackColor();
60
61 oBtn.onclick = function(){
62 changeBackColor();
63 for(var i=0;i<oTab.tBodies[0].rows.length;i++){
64 var oCells = oTab.tBodies[0].rows[i].cells[1].innerHTML.toLowerCase();
//把获取到的值都转换成小写或这大写,便于查询
65 var oTxtVal = oTxt.value.toLowerCase();
66 //search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。如果没有找到任何匹配的子串,则返回 -1。
67 if(oCells.search(oTxtVal) != -1){
68 oTab.tBodies[0].rows[i].style.background = "red";
69 }
70 }
71 }
72
73 function changeBackColor(){
74 for(var i=0;i<oTab.tBodies[0].rows.length;i++){
75
76 oTab.tBodies[0].rows[i].onmouseover=function(){
77 oldColor = this.style.background;
78 this.style.background = "yellow";
79 }
80
81 oTab.tBodies[0].rows[i].onmouseout=function(){
82 this.style.background = oldColor;
83 }
84
85
86 if(i%2==0){
87 oTab.tBodies[0].rows[i].style.background = "#ccc";
88 }else{
89 oTab.tBodies[0].rows[i].style.background = "";
90 }
91
92 }
93 }
94
95
96 }
97 </script>
98 </html>