一、get方式拼接
// 定义url字符串拼接的方法
const setUrlQuery = (options) => {
let {url,query} = options;
if(!url) return '';
if(query) {
let queryArr = [];
for (const key in query) {
if (query.hasOwnProperty(key)) {
queryArr.push(`${key}=${query[key]}`)
}
}
if(url.indexOf('?') !== -1) {
url =`${url}&${queryArr.join('&')}`
} else {
url =`${url}?${queryArr.join('&')}`
}
}
return url;
}
二、目录方式拼接
<html>
<head>
<script>
$(function(){
/* bieanju原创多条件筛选 */
$('.filter').click(function(){
var name = $(this).attr('data-name');
var value = $(this).attr('value');
var url = window.location.href;
var jump_url;
/* 无参数正常跳转 */
if(typeof(name) == "undefined" || typeof(value) == "undefined"){
window.location.href = url;
return false;
}
/* 如果当前地址不是以"/"结束追加 */
if((url.charAt(url.length-1) == "/") == false){
url += "/";
}
if(url.indexOf(name) > 0){
var data = url.split('/');
for(i in data){
if(data[i] == name){
data[parseInt(i)+parseInt(1)] = value;
}
}
jump_url = data.join("/");
}else{
jump_url = url+name+"/"+value+"/";
}
window.location.href = jump_url;
return false;
})
})
</script>
</head>
<body>
条件一:<a href="http://www.test.com/catid/1" data-name="catid" value="1"> 企业</a><a data-name="catvalue" value="2" href="http://www.test.com/catid/1" >商城</a>
条件二:<a href="http://www.test.com/price/100-200" data-name="price" value="100-200"> 100-200</a><a data-name="price" value="200-300" href="http://www.test.com/price/1" >200-300</a>
条件三:<a href="http://www.test.com/star/1" data-name="star" value="1"> 一星</a><a data-name="star" value="2" href="http://www.test.com/star/1" >二星</a>
</body>
</html>
三、增加参数
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;
}
网友评论