很多时候能在前端用js实现的数据交互,要比后台套页面实现起来要简单的多,项目中要实现多重筛选的功能,没有做成接口,那就只能js实现url的拼接转换刷新页面,本质就是改变get传参里参数值,这里先简单介绍下window.location里属性值
属性 | 描述 |
href | 完整的URL |
pathname | 当前URL的主机名 |
host | 当前URL的主机名和端口号 |
port | 当前URL的端口号 |
hash | 从#开始的URL(锚) |
search | 从?开始的URL(查询部分) |
protocol | 当前URL的协议 |
js对url的操作无非就是对这几个属性值的操作,html自定义属性,记录对应的参数和值
<div "> <a href="javascript:void(0);" class="remove-sel selected" style="padding-left: 0;" type="sentiment">全部</a> <a href="javascript:void(0);" class="add-sel" type="sentiment" value="1">负面</a> <a href="javascript:void(0);" class="add-sel" type="sentiment" value="2">中性</a> <a href="javascript:void(0);" class="add-sel" type="sentiment" value="3">正面</a> </div>
增加参数
function addParama(key, val) { var search = window.location.search; if (search.indexOf('?') != -1) { search = search.substring(1); var search_arr = search.split('&'); var url_arr = []; var exists = 0; for (var i = 0; i < search_arr.length; i++) { if (!search_arr[i]) continue; var temp = search_arr[i].split('='); if (key == temp[0]) { exists = 1; url_arr.push(key + '=' + val); } else { if (temp[0] != 'page' && temp[0] != 'token') { url_arr.push(search_arr[i]); } } } if (!exists) url_arr.push(key + '=' + val); var url = window.location.pathname + '?' + url_arr.join('&'); } else { var url = window.location.pathname + '?' + key + '=' + val; } window.location.href = url; }
删除参数
function delParama(key) { var search = window.location.search; var url = window.location; if (search.indexOf(key) != -1) { search = search.substring(1); var search_arr = search.split('&'); var url_arr = []; for (var i = 0; i < search_arr.length; i++) { var temp = search_arr[i].split('='); if (key != temp[0]) { url_arr.push(search_arr[i]); } } if (url_arr.length == 0){ url = window.location.pathname; }else { url = window.location.pathname + '?' + url_arr.join('&'); } } window.location.href = url; }