Skip to content

Instantly share code, notes, and snippets.

@think2011
Created January 25, 2016 05:06
Show Gist options
  • Save think2011/de4274abd5c84c1c7e2d to your computer and use it in GitHub Desktop.
Save think2011/de4274abd5c84c1c7e2d to your computer and use it in GitHub Desktop.
给url额外添加参数
/**
* 给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