【案例】商品查詢案例-利用數組新增方法操作數據
<!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: 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;
}
</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: 'oppo',
price: 999
}, {
id: 3,
pname: '榮耀',
price: 1299
}, {
id: 4,
pname: '華爲',
price: 1999
}, ];
// 1. 獲取相應的元素
var tbody = document.querySelector('tbody');
var search_price = document.querySelector('.search-price');
var start = document.querySelector('.start');
var end = document.querySelector('.end');
var product = document.querySelector('.product');
var search_pro = document.querySelector('.search-pro');
setDate(data);
// 2. 把數據渲染到頁面中
function setDate(mydata) {
// 先清空原來tbody 裏面的數據
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 newData = data.filter(function (value) {
return value.price >= start.value && value.price <= end.value;
})
// 把篩選完之後的對象渲染到頁面中
setDate(newData);
});
// 4. 根據商品名稱查找商品
// 如果查詢數組中唯一的元素, 用some方法更合適,因爲它找到這個元素,就不在進行循環,效率更高]
search_pro.addEventListener('click', function () {
var arr = [];
data.some(function (value) {
if (value.pname === product.value) {
arr.push(value);
return true; // return 後面必須寫true
}
});
// 把拿到的數據渲染到頁面中
setDate(arr);
});
</script>
</body>
</html>