Created
January 25, 2016 05:06
-
-
Save think2011/de4274abd5c84c1c7e2d to your computer and use it in GitHub Desktop.
给url额外添加参数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 给url额外添加参数 | |
* @param url | |
* @param {object} params 要添加的参数 | |
* @returns {*|Element} | |
*/ | |
function patchUrlParams (url, params) { | |
var a = document.createElement('a'); | |
var _params = {}; | |
a.href = url; | |
// 提取参数 | |
if (a.search) { | |
var searchStr = a.search.slice(1).split('&'); | |
while (searchStr.length) { | |
var param = searchStr.splice(0, 1)[0]; | |
_params[param.split('=')[0]] = param.split('=')[1]; | |
} | |
} | |
// 继承参数 | |
for (var p in params) { | |
if (!params.hasOwnProperty(p)) continue; | |
_params[p] = params[p]; | |
} | |
// 设置参数 | |
a.search = ''; | |
for (var p in _params) { | |
if (!_params.hasOwnProperty(p)) continue; | |
if (_params[p] == undefined) { | |
_params[p] = ''; | |
} | |
a.search = a.search += ('&' + p + '=' + _params[p]); | |
} | |
a.search = a.search.slice(2); | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment