利用es6的数组方法实现了一个可以实现商品价格区间查询,商品名称查询的界面 。
界面如下:
<!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: 600px;
border: 1px solid #000;
border-collapse: collapse;
margin: 20px auto;
}
td,
th {
border: 1px solid #ccc;
text-align: center;
height: 50px;
}
tr:hover {
background-color: whitesmoke;
}
input {
width: 50px;
padding: 0;
margin: 0;
}
input:focus {
outline: 2px solid #51c9ff;
border: 1px solid #fff;
border-radius: 2px;
}
.search {
width: 600px;
margin: 30px auto;
}
button {
background-color: #51c9ff;
color: #fff;
border: none;
border-radius: 3px;
width: 50px;
height: 25px;
}
</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: '扫地机器人',
price: 999
}, {
id: 3,
pname: '电饭锅',
price: 1299
}, {
id: 4,
pname: '榨汁机',
price: 1999
}, ];
// 获取相应的元素
var tbody = document.querySelector('tbody');
var start = document.querySelector('.start');
var end = document.querySelector('.end');
var search_price = document.querySelector('.search-price');
var product = document.querySelector('.product');
var search_pro =document.querySelector('.search-pro');
setData(data);
function setData(mydata){
// 要写一个形参
//把数据渲染到页面中
tbody.innerHTML = '';
mydata.forEach(function(value){
// console.log(value); value是data中的每个对象
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +value.id+ '</td><td>' +value.pname+ '</td><td>' +value.price+ '</td>'
tbody.appendChild(tr);
});
}
//价格查询
var new_data=[];
search_price.addEventListener('click',function(){
var new_data = data.filter(function(value){
return value.price >= start.value && value.price <= end.value;
});
setData(new_data);
})
// 商品查询
// 如果查询数组中唯一的元素,用some方法更合适,因为找到这个元素后,就不再进行循环,效率更高。
search_pro.addEventListener('click',function(){
var arr = [];
data.some(function(value){
// 注意some返回的是boolean类型的值 所以需要设定一个空数组来接收符合条件的数据
if(value.pname === product.value){
arr.push(value);
return true; // return后面必须写true
}
});
// 渲染数据
setData(arr);
})
</script>
</body>
</html>