<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
header {
text-align: center;
margin-top: 40px;
}
main {
text-align: center;
}
input.min {
width: 40px;
}
table {
border: 1px solid #000;
border-collapse: collapse;
margin: 40px auto;
}
th,
td {
border: 1px solid #000;
padding: 0 20px;
}
td:nth-child(2) {
padding: 0 100px;
}
</style>
</head>
<body>
<div class="container">
<header>
<span>按照价格查询:</span>
<input type="text" class="min" id="min">
<span>-</span>
<input type="text" class="min" id="max">
<button id="search">搜索</button>
<span>按照商品名称查询:</span>
<input type="text" class="min" id="brand">
<button id="brand-search">搜索</button>
</header>
<main>
<table>
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>1</td>
<td>小米</td>
<td>3999</td>
</tr>
<tr>
<td>2</td>
<td>oppo</td>
<td>999</td>
</tr>
<tr>
<td>3</td>
<td>荣耀</td>
<td>1299</td>
</tr>
<tr>
<td>4</td>
<td>华为</td>
<td>1999</td>
</tr> -->
</tbody>
</table>
</main>
</div>
<script>
var data = [
{ id: 1, name: '小米', price: 2999 },
{ id: 2, name: '华为', price: 1999 },
{ id: 3, name: 'oppo', price: 3999 },
{ id: 4, name: '苹果', price: 999 }
]
function show(data) {
// 动态添加静态数据到表格里面
var tbody = document.querySelector('tbody');
tbody.innerHTML = '';
data.forEach(function (item, index, arr) {
var tr = document.createElement('tr');
tr.innerHTML = '<tr> <td>' + item.id + '</td> <td>' + item.name + '</td> <td>' + item.price + '</td> </tr>';
tbody.appendChild(tr);
})
}
show(data);
// 搜索商品价格区间再显示出来
let search = document.querySelector('#search');
search.addEventListener('click', function () {
let min = document.querySelector('#min').value;
let max = document.querySelector('#max').value;
let newArr = [];
newArr = data.filter(function (item, index, arr) {
return item.price >= min && item.price <= max
})
show(newArr);
})
// 搜索商品名称再显示出来
// 如果查询数组中唯一的元素,用some方法更合适,因为它找到这个元素,就不再进行循环,效率更高
let brand = document.querySelector('#brand-search');
brand.addEventListener('click',function(){
let name = document.querySelector('#brand').value;
let newData = [];
// some遇到了return true会立即终止循环
newArr = data.some(function (item, index, arr) {
if(item.name == name){
newData.push(item);
return true;
}
})
show(newData);
})
</script>
</body>
</html>
第二课:ES5中新增的方法数组方法案例:查询商品(2021/4/16)
最新推荐文章于 2022-10-17 18:59:06 发布