背景:页面数据由后台渲染
需求:筛选条件课程类目、是否收费、课程类型(线上、线下),三个参数,要求点击对应选项通过地址栏传参筛选数据。
<div class="filterBox">
<div class="cate-tab flex_between">
<div class="cate-item pointer" data-CategoryId="">全部课程</div>
@foreach (var item in CourseCategoryList)
{
<div data-CategoryId="@item.CategoryId" class=" cate-item pointer"> @item.CategoryName</div>
}
</div>
<div class="opt-tab flex_between">
<a class="isFree pointer active" data-IsFree="">全部</a>
<a class="isFree pointer" data-IsFree="0">付费</a>
<a class="isFree pointer" data-IsFree="1" >免费</a>
<div class="line"></div>
<a class="type pointer" data-Type="">全部</a>
<a class="type pointer" data-Type="1">线上</a>
<a class="type pointer" data-Type="2">线下</a>
</div>
</div>
getUrlParams(); //获取地址栏参数,存成对象
initStyle('IsFree'); //根据地址栏参数高亮当前页面所选的筛选项
initStyle('CategoryId');
initStyle('Type');
$('.cate-item').on('click', (e) => { //选项点击事件,更新对应参数值,并跳转
changeParams('CategoryId',e)
})
$('.type').on('click', (e) => {
changeParams('Type',e)
})
$('.isFree').on('click', (e) => {
changeParams('IsFree',e)
})
function getUrlParams() {
let paramsArr = paramString.replace('?','').split('&')
if(paramString){
paramsArr.map(i=>{
let key = i.split('=')[0]
let value = i.split('=')[1]
paramsObj[key] = value
return i
})
}
}
function initStyle(key){
let $keyDom = $(`[data-${key}]`)
if(key in paramsObj){
for(let i=0;i<$keyDom.length;i++) {
$keyDom.eq(i).removeClass('active')
if($keyDom.eq(i).attr(`data-${key}`)===paramsObj[key]){
$keyDom.eq(i).addClass('active')
}
}
}else{
$(`[data-${key}=""]`).addClass('active')
}
}
function changeParams(dataKey, e) {
let key = $(e.currentTarget).attr(`data-${dataKey}`)
if (!paramString) { //url无参数
location.href = location.pathname + '?' + dataKey + '=' + key //加第一个参数
} else if (dataKey in paramsObj) { //有参数,点击的参数是否已有
if (key) { //已有且新选属性值key不为空则替换
paramsObj[dataKey] = key
} else {
delete paramsObj[dataKey] //key为空则删除该属性
}
//更新后将已有参数拼成url
let keyArr = Object.keys(paramsObj)
let valArr = Object.values(paramsObj)
let pArr = []
for (let k = 0; k < keyArr.length; k++) {
pArr[k] = keyArr[k] + '=' + valArr[k]
}
let newLink = ''
if (pArr.length > 0) {
newLink = '?' + pArr.join('&') //如果有参数 拼起来
}
location.href = location.pathname + newLink //没有,添加在后面
} else {
location.href = location.href + '&' + dataKey + '=' + key
}
}