思路
就是利用数组的filter方法进行过滤,不难
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<select name="" id="">
<option value="0">请选择销量范围</option>
<option value="1"><100</option>
<option value="2">100~500</option>
<option value="3">>500</option>
</select>
<ul>
<li>牛客logo马克杯</li>
<li>无盖星空杯</li>
<li>老式茶杯</li>
<li>欧式印花杯</li>
</ul>
<script>
var cups = [
{ type: 1, price: 100, color: 'black', sales: 60, name: '牛客logo马克杯' },
{ type: 2, price: 40, color: 'blue', sales: 100, name: '无盖星空杯' },
{ type: 4, price: 60, color: 'green', sales: 200, name: '老式茶杯' },
{ type: 3, price: 50, color: 'green', sales: 600, name: '欧式印花杯' },
]
var select = document.querySelector('select')
var ul = document.querySelector('ul')
// 补全代码
let res = [] // 存放结果
// 更新视图
function updateDOM() {
ul.innerHTML = ''
let str = ''
for (let i = 0; i < res.length; i++) {
str += `<li>${res[i].name}</li>`
}
ul.innerHTML = str
}
select.onchange = function () {
const value = this.options[this.options.selectedIndex].value
if (value == 1) {
res = cups.filter((item) => {
return item.sales < 100
})
updateDOM()
} else if (value == 2) {
res = cups.filter((item) => {
return item.sales >= 100 && item.sales <= 500
})
updateDOM()
} else if (value == 3) {
res = cups.filter((item) => {
return item.sales > 500
})
updateDOM()
}
}
</script>
</body>
</html>