ZhangYang's Blog

【实战】封装获取url的querystring参数

需求

1
2
3
4
http://xxx.com/index.html?a=1
$.bom.search('a')
$.bom.search('a', 'xxx')
http://xxx.com/index.html?a=xxx

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
window.$ = function(){
let array = []
return array
}
$.bom = {
openAtCenter: function(width, height, url){
window.open(url, '_blank', `
width=${width}px,height=${height}px,
screenX=${screen.width/2 - width/2}px,
screenY=${screen.height/2 - height/2}px
`)
},
search: function(name, value){
let searchAll = function(){
let result = {}
let search = window.location.search
// 去掉?
if(search[0] === '?'){
search = search.slice(1)
}
// 用 & 分隔成数组
let searchArray = search.split('&')
// 遍历数组
for(var i =0;i<searchArray.length; i++){
let parts = searchArray[i].split('=')
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1] || '')
}
return result
}
let result = searchAll()
if(value === undefined){
return result[name]
}else{
if(result[name] === undefined){
location.search += `&${encodeURIComponent(name)}=${encodeURIComponent(value)}`
}else{
result[name] = encodeURIComponent(value)
let newSearch = '?'
for(let key in result){
newSearch += `${encodeURIComponent(key)}=${encodeURIComponent(result[key])}&`
}
location.search = newSearch
}
}
}
}