效果图
通过js实现一个简单的商城物品筛选功能
因为主要是js思想,所以页面搭建很简陋
html
<div class="filter">
<a href="javascript:;">全部区间</a>
<a data-index='1' href="javascript:;">100以内</a>
<a data-index='2' href="javascript:;">100-300</a>
<a data-index='3' href="javascript:;">300以外</a>
</div>
<div class="list">
<div class="item">
<img src="sc.html/GFX 100S.jpg" alt="">
<p class="name">12</p>
<p class="price">12</p>
</div>
</div>
css
(其中的点击切换背景颜色使用的是:active和:focus)
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.filter {
margin: 200px 0px 50px 500px;
}
a {
display: inline-block;
width: 150px;
height: 40px;
text-align: center;
line-height: 40px;
border: 1px solid black;
text-decoration: none;
color: black;
}
.filter a:active,
.filter a:focus {
background-color: #05943c;
color: #fff;
}
.list {
width: 630px;
display: flex;
justify-content: space-around;
/* background-color: pink; */
margin: 10px 500px;
text-align: center;
}
.item {
width: 200px;
height: 200px;
margin: 5px;
}
.item img {
width: 100%;
height: 130px;
}
.price {
color: red;
}
接下来是js
这是一组要渲染到页面上的数据,一般由后台传送过来,我们没有后台,所以自己写数据
const goodsList = [
{
id:'4001172',
name:'相机1',
price:'199.00',
picture:'sc.html/GFX100.jpg',
},
{
id:'4001172',
name:'相机2',
price:'99.00',
picture:'sc.html/GFX100.jpg',
},
{
id:'4001172',
name:'相机3',
price:'299.00',
picture:'sc.html/GFX100.jpg',
},
{
id:'4001172',
name:'相4',
price:'399.00',
picture:'sc.html/GFX100.jpg',
},
]
封装一组函数
将goodsList数组作为实参传入形参arr内,先声明一个空的字符转,利用forEach遍历数组,其中为了简化方便操作代码,使用了解构(所谓解构就是对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。变量名与属性名一致。真正被赋值的是后者,而不是前者)。将页面内容利用模板字符串放置到提前声明的空字符串中,然后渲染到页面。
function render(arr) {
// 声明空字符串
let str = ''
// 遍历数组
arr.forEach(item => {
// 解构
const {name,price,picture} = item
str += `
<div class="item">
<img src=${picture} alt="">
<p class="name">${name}</p>
<p class="price">${price}</p>
</div>
`
});
document.querySelector('.list').innerHTML = str
}
render(goodsList)
接下来就是点击筛选功能
同样也是用了解构
将goodsList赋值给arr
利用自定义属性的序号(dataset.index)获取点击的是哪个区间,然后用filter()方法筛选出价格内容在此区间的商品,将goodsList中符合条件的对象赋值给arr
最后调用函数render()渲染到页面上,从而完成筛选的功能。
document.querySelector('.filter').addEventListener('click',e => {
// 解构
const {tagName,dataset} = e.target
if(tagName==='A') {
let arr = goodsList
if(dataset.index ==='1') {
// console.log(11);
arr = goodsList.filter(item => item.price>0 && item.price<=100)
}else if (dataset.index ==='2') {
// console.log(22);
arr = goodsList.filter(item => item.price>=100 && item.price<=300)
}else if (dataset.index ==='3') {
// console.log(33);
arr = goodsList.filter(item => item.price>=300)
}
// 渲染函数
render(arr)
}
})