需求分析
1.能够根据价格搜索出对应的商品;
2.能够根据商品名称查询出对应商品;
实现效果
1.
2.
源代码
<style>
.search{
margin: 0 auto;
margin-bottom:10px;
}
input{
width: 50px;
}
table,table tr th, table tr td { border:1px solid #000; }
table { width: 500px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse; padding:2px;}
</style>
<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-name">查询</button>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var data = [{
id:1,
pname:'小米',
price:1000
},
{
id:2,
pname:'华为',
price:2000
},
{
id:3,
pname:'荣耀',
price:3999
},
{
id:4,
pname:'诺基亚',
price:7000
}];
//1.先获取相应是元素
var tbody = document.querySelector('tbody');
var search_price = document.querySelector('.search-price');
var start = document.querySelector('.start');
var end = document.querySelector('.end');
var search_name = document.querySelector('.search-name');
var product = document.querySelector('.product');
setDate(data);
//2.把数据渲染到页面中
function setDate(mydata){
tbody.innerHTML = '';
mydata.forEach(function(value){
var tr = document.createElement('tr');
tr.innerHTML = '<td>'+value.id+'</td><td>'+value.pname+'</td><td>'+value.price+'</td>';
tbody.appendChild(tr);
});
}
//3.根据价格查询商品
//当我们点击了按钮,就可以根据我们的商品价格去筛选数组里面的对象
//搜索按钮
search_price.addEventListener('click',function(){
var newGoods = data.filter(function(value){
return value.price >= start.value && value.price <= end.value;
})
console.log(newGoods);
setDate(newGoods)
});
//4.根据商品名称查询商品
//如果查询数组中唯一的元素,用some方法更合适,因为找到这个元素,就不在进行循环,效率更高
search_name.addEventListener('click',function(){
var arr = [];
data.some(function(value){
if(value.pname === product.value){
console.log("2",value);
arr.push(value);
return true;//用some()后面只能写true和false
}
});
//把拿到的数据渲染到页面中
setDate(arr)
})
</script>
主要用到的方法
forEach()、filter()和some()方法
注意: 如果查询数组中唯一的元素,用some方法更合适,因为找到这个元素,就不在进行循环,效率更高。