<!DOCTYPE html>
<html lang="en">
<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>
<style>
table {
width: 400px;
border: 1px solid #000;
border-collapse: collapse;
margin: 0 auto;
}
td,
th {
border: 1px solid #000;
text-align: center;
}
input {
width: 50px;
}
.search {
width: 600px;
margin: 20px auto;
}
</style>
</head>
<body>
<div class="search">
按照价格查询: <input type="text" class="start"> - <input type="text" class="end"> <button
class="search-price">搜索</button> 按照商品名称查询: <input type="text" class="product"> <button
class="search-pro">查询</button>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var data = [{
id: 1,
pname: '小米',
price: 3999
}, {
id: 2,
pname: 'oppo',
price: 999
}, {
id: 3,
pname: '荣耀',
price: 1299
}, {
id: 4,
pname: '华为',
price: 1999
}, ];
// 1. 获取相应的元素
var btn = document.getElementsByClassName('search-price')[0]
var search = document.getElementsByClassName('search-pro')[0]
var thead = document.querySelector('thead')
// 2. 把数据渲染到页面中
var tit = thead.innerHTML
data.forEach(function(v,i) {
thead.innerHTML += '<tr><td>'+data[i].id+'</td>'+'<td>'+data[i].pname+'</td>'+'<td>'+data[i].price+'</td></tr>'
})
// 3. 根据价格查询商品
btn.onclick = function() {
var start = document.getElementsByClassName('start')[0].value
var end = document.getElementsByClassName('end')[0].value
thead.innerHTML = tit
data.forEach(function(v,i) {
// 4. 把筛选完之后的对象渲染到页面中
if(data[i].price > start && data[i].price < end) {
thead.innerHTML += '<tr><td>'+data[i].id+'</td>'+'<td>'+data[i].pname+'</td>'+'<td>'+data[i].price+'</td></tr>'
}
})
}
// 5. 根据商品名称查找商品
search.onclick = function() {
var pro = document.getElementsByClassName('product')[0].value
thead.innerHTML = tit
data.forEach(function(v,i) {
// 6. 把筛选完之后的对象渲染到页面中
if(data[i].pname == pro) {
thead.innerHTML += '<tr><td>'+data[i].id+'</td>'+'<td>'+data[i].pname+'</td>'+'<td>'+data[i].price+'</td></tr>'
}
})
}
</script>
</body>
</html>