样式的填充
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;
}
页面的骨架
<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>
逻辑功能的实现
//数据集定义
const arr = [
{
id:1,
name:'小米',
price:888
},
{
id:2,
name:'苹果',
price:8000
},
{
id:3,
name:'大米',
price:8848
},
{
id:4,
name:'小麦',
price:1688
},
];
function setData(mydata){
const tbody =document.querySelector('tbody')
tbody.innerHTML = ''
mydata.forEach(
i => {
let tr = `<td>${i.id}</td><td>${i.name}</td><td>${i.price}</td>`
tbody.insertAdjacentHTML('beforeend',tr)
});
}
let that
class Search{
"use strict";
constructor(search){
that = this
this.search = document.querySelector(search)
this.start = this.search.querySelector('.start')//开始价格范围
this.end = this.search.querySelector('.end')//结束价格范围
this.search_price = this.search.querySelector('.search-price')//价格检索按钮
this.search_pro = this.search.querySelector('.search-pro')//名字检索按钮
this.ptoduct = this.search.querySelector('.product')
this.init()//主函数
}
init(){
this.search_price.addEventListener('click',this.searchPrice)
this.search_pro.addEventListener('click',this.searchName)
setData(arr)//视图渲染
}
// 价格检索
searchPrice(){
let newData = arr.filter(
i=>{
return i.price >= that.start.value&&i.price< that.end.value
//不建议将return后面的判断语句分开
})
console.log(newData);
setData(newData)
}
//名字检索
searchName(){
let data = [];
// console.log(that.ptoduct.value)
arr.some(i=>{
if(i.name === that.ptoduct.value){
data.push(i)
return true
}
})
setData(data)
}
}
new Search(`.search`)