实例
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <input type="text"><button onclick="search(this)">搜索</button> <table border="1" width="800" align="center" id="mytab"> <tr> <td>ID</td> <td>Name</td> <td>Sex</td> <td>Age</td> <td>City</td> </tr> <tr> <td>1</td> <td>Jack</td> <td>人妖</td> <td>80</td> <td>泰国</td> </tr> <tr> <td>2</td> <td>Jack</td> <td>人妖</td> <td>80</td> <td>泰国</td> </tr> <tr> <td>3</td> <td>john</td> <td>男</td> <td>80</td> <td>泰国</td> </tr> <tr> <td>4</td> <td>Tom</td> <td>男</td> <td>80</td> <td>泰国</td> </tr> <tr> <td>5</td> <td>Rose</td> <td>女</td> <td>80</td> <td>泰国</td> </tr> </table> </body> <script type="text/javascript"> var mytab = document.getElementById('mytab'); function search(obj){ console.log(obj.previousSibling.value); //获取input框中的搜索内容,搜索关键字 var keyword = obj.previousSibling.value; if(keyword ==''){ return false; } //遍历所有的行 for(var i=1;i<mytab.rows.length;i++){ //还原原来的颜色 mytab.rows[i].bgColor='white'; //遍历单元格 for(var j=0;j<mytab.rows[i].cells.length;j++){ //获取每个单元格的值 if(mytab.rows[i].cells[j].innerHTML.indexOf(keyword)!=-1){ mytab.rows[i].bgColor="yellowgreen"; } } } } </script> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例