HTML部分
CSS部分
JS部分
完整代码
<!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>价格查询</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.content {
width: 900px;
margin: 100px auto;
/* background :red; */
}
.search1 {
font-size: 28px;
}
.search1 input {
width: 300px;
height: 36px;
outline: none;
}
.search2 {
font-size: 28px;
}
.search2 input {
width: 300px;
height: 36px;
outline: none;
margin-top: 20px;
}
button {
width: 70px;
height: 50px;
margin-left: 20px;
border-radius: 5px;
}
table {
width: 600px;
margin: 20px auto;
text-align: center;
}
table th {
background-color: aqua;
}
</style>
</head>
<body>
<div class="content">
<div class="search1">
<span>按价格查询</span><input type="text" class="start"> <span>-</span> <input type="text" class="end"><button
class="search_price">查询</button>
</div>
<div class="search2">
<span>按名称查询</span><input type="text" class="product"><button class="search_product">查询</button>
</div>
<table border="2" class="table">
<thead>
<th>id</th>
<th>名称</th>
<th>价格</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
<script>
var data = [{
id: 1,
name: "保时捷",
price: 100
},
{
id: 2,
name: "宝马",
price: 50
},
{
id: 3,
name: "奔驰",
price: 100
},
{
id: 4,
name: "法拉利",
price: 200
},
{
id: 5,
name: "兰博基尼",
price: 400
}, {
id: 6,
name: "雷克萨斯",
price: 200
}, {
id: 7,
name: "野马",
price: 300
}
];
// 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_product = document.querySelector(".search_product");
setdata(data);
// 2.通用渲染数据封装
function setdata(mydata) {
// 先清空tbody里面的数据
tbody.innerHTML = ""
mydata.forEach(function (item) {
console.log(item);
var tr = document.createElement('tr');
tr.innerHTML = `<td>` + item.id + `</td><td>` + item.name + `</td><td>` + item.price + `</td>`;
tbody.appendChild(tr);
})
}
// 3.根据价格查询商品
// 筛选对象
search_price.addEventListener("click", function () {
//判断输入是否为空 不加判断单独点击会清空渲染
if (start.value != "" && end.value != "") {
// alert(1)
var newdata = data.filter(function (item) {
// console.log(item);
return item.price >= start.value && item.price <= end.value
})
console.log(newdata);
// 筛选完渲染
setdata(newdata);
}
})
// 4.根据名称查询商品
search_product.addEventListener("click", function () {
//判断输入是否为空 不加判断单独点击会清空渲染
if (product.value != "") {
var arr = []
data.some(function (value) {
if (value.name === product.value) {
console.log(value);
arr.push(value)
return true
}
});
setdata(arr);
}
})
</script>