【实战】封装获取url的querystring参数 发表于 2018-09-28 | 分类于 JavaScript 需求1234http://xxx.com/index.html?a=1$.bom.search('a') $.bom.search('a', 'xxx')http://xxx.com/index.html?a=xxx 源代码 12345678910111213141516171819202122232425262728293031323334353637383940414243444546window.$ = 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 } } }}