查询商品案例
1.把数据渲染到页面中(forEach)
2.根据价格显示数据(filter)
3.根据商品名显示数据
效果如下:
代码如下:
html
<div id="app">
<div class="begin">
按照价格查询:
<input type="text" class="start">
-
<input type="text" class="end">
<input type="button" value="搜索" class="pri">
按照商品名称查询:
<input type="text" class="product">
<input type="button" value="查询" class="pro">
</div>
<div class="end">
<table class="tb">
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
css
<style>
#app{
width: 600px;
height: 500px;
margin: 10px auto;
}
.begin{
padding: 10px;
border: 1px solid black;
margin-bottom: 20px;
}
.end{
border: 1px solid black;
height: 100%;
}
input{
width: 50px;
}
.tb{
width: 95%;
border-collapse: collapse;
margin: 10px auto;
}
.tb th{
background-color: #0094ff;
}
.tb th,.tb td{
border: 1px solid black;
text-align: center;
}
</style>
js
//利用新增数组方法操作数据
var list=[
{
id:1,
name:'小米',
price:3999
},
{
id:2,
name:'oppo',
price:999
},
{
id:3,
name:'荣耀',
price:1299
}
];
//1.获取相应的元素
var tbody = document.querySelector('tbody');
var pri = document.querySelector(".pri");
var start = document.querySelector('.start');
var end = document.querySelector('.end');
var product = document.querySelector('.product')
var pro = document.querySelector('.pro')
setList(list)
//2.把数据渲染到页面中
function setList(mylist){
//先清空原来tbody里面的数据
tbody.innerHTML=""
mylist.forEach(function(value){
// console.log(value);
var tr = document.createElement("tr");
tr.innerHTML = '<td>' + value.id +'</td><td>' + value.name +'</td><td>' + value.price +'</td>'
tbody.appendChild(tr);
});
}
//3.根据价格查询商品
//当我们点击了按钮,就可以根据我们的商品价格去筛选数组里面的对象。
pri.addEventListener('click',function(){
// console.log(111)
var newList = list.filter(function(value){
return value.price >= start.value && value.price <= end.value;
});
console.log(newList);
//把筛选完之后的对象渲染到页面中
setList(newList)
});
//4.根据商品名称查找商品
//如果查询数组中唯一的元素,用some方法更合适,因为它找到这个元素,就不在进行循环,效率更高
pro.addEventListener('click',function(){
var arr = [];
list.some(function(value){
if(value.name === product.value){
// console.log(value);
arr.push(value);
return true; //return 必须后面写true
}
});
//把拿到的数据渲染到页面中
setList(arr)
})