一、精确查找
<!DOCTYPE >
<html>
<head>
<title></title>
<meta charset="utf-8">
<script>
window.onload = function() {
var oTab = document.getElementById('tab1');
var oTbody = oTab.tBodies[0];
var oName = document.getElementById('name'); // 姓名
var oSearchBtn = document.getElementById('search'); // 搜索(按钮)
oSearchBtn.onclick = function() {
for(var i = 0; i < oTbody.rows.length; i++) {
var name = oTbody.rows[i].cells[1].innerHTML;
if(name == oName.value) {
oTbody.rows[i].style.background = 'yellow';
} else {
oTbody.rows[i].style.background = '';
}
}
}
}
</script>
</head>
<body>
姓名:<input type="text" name="name" id="name" value="张三" />
<input type="button" name="search" id="search" value="搜索" />
<div id="">搜索结果高亮显示
</div>
<table id="tab1" width="300" border="1">
<thead>
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Blue</td>
<td>27</td>
</tr>
<tr>
<td>2</td>
<td>张三</td>
<td>23</td>
</tr>
<tr>
<td>3</td>
<td>李四</td>
<td>28</td>
</tr>
<tr>
<td>4</td>
<td>王五</td>
<td>25</td>
</tr>
<tr>
<td>5</td>
<td>张伟</td>
<td>24</td>
</tr>
</tbody>
</table>
</body>
</html>
image.png
二、模糊查找
name.search(sName) != -1
oSearchBtn.onclick = function() {
if(!oName.value) {
alert("请输入关键字")
}
// 遍历整个表
for(var i = 0; i < oTbody.rows.length; i++) {
var name = oTbody.rows[i].cells[1].innerHTML.toLowerCase();
var sName = oName.value.toLowerCase();
if(name.search(sName) != -1) { // 模糊查询
oTbody.rows[i].style.background = 'yellow';
} else {
oTbody.rows[i].style.background = '';
}
}
}
image.png
网友评论