var UrlArgent = { Parsed: false, //是否已解析 Cache: {}, //緩存值 ParseArg: function () { // 解析地址欄的參數值 UrlArgent.Parsed = true; var url = location.search; if (-1 == url.indexOf('?')) return; var args = url.substr(1).split("&"); for (var i = 0; i < args.length; i++) { var tmp = args[i]; var pos = tmp.indexOf('='); if (-1 == pos) continue; UrlArgent.Cache[tmp.substr(0, pos)] = tmp.substr(pos + 1); } }, GetItem: function (queryStringName, defaultVal) { // 獲取單個項目的值 queryStringName大小寫敏感,及區分大小寫 if (UrlArgent.Parsed == false) UrlArgent.ParseArg(); return UrlArgent.Cache[queryStringName] || (typeof (defaultVal) == 'undefined' ? '' : defaultVal.toString()); }, GetItemIgnore: function (queryStringName, defaultVal) { // 獲取單個項目的值 queryStringName忽略大小寫 if (UrlArgent.Parsed == false) UrlArgent.ParseArg(); for (var k in UrlArgent.Cache) { if (UrlArgent.Cache.hasOwnProperty(k) == false) continue; //只取私有屬性 if (k.toLowerCase() == queryStringName.toLowerCase()) return UrlArgent.Cache[k]; } return (typeof (defaultVal) == 'undefined' ? '' : defaultVal.toString()); }, GetUrl: function (newValue, ignore) { // 獲取url參數 newValue增長或修改的值 ignore關鍵字是否忽略大小寫,true忽略大小寫其餘值大小寫敏感 if (typeof (newValue) != 'object') return location.search.substr(1); //原樣返回 if (UrlArgent.Parsed == false) UrlArgent.ParseArg(); var url = []; for (var k in UrlArgent.Cache) { if (UrlArgent.Cache.hasOwnProperty(k) == false) continue; //只取私有屬性 var val = UrlArgent.Cache[k]; //默認是原值 for (var n in newValue) { if (newValue.hasOwnProperty(n) == false) continue; if ((k == n) || (ignore == true && k.toLowerCase() == n.toLowerCase())) { //須要替換原來的值 val = newValue[n].toString(); //賦新值 newValue[n] = null; //清除設置了值的項 } } url.push(k + '=' + val); } for (var n in newValue) { //新增長的鍵值 if (newValue.hasOwnProperty(n) == false) continue; if (newValue[n] == null) continue; url.push(n + '=' + newValue[n].toString()); } return url.join('&'); } };
使用:javascript
var a = UrlArgent.GetItem('x'); var x = UrlArgent.GetItem('x', 0); var y = UrlArgent.GetItemIgnore('X'); var s = UrlArgent.GetUrl(); var w = UrlArgent.GetUrl({ "x": "vv", "ismobilE": "vs" }); var z = UrlArgent.GetUrl({ "X": "vv", "ismobilE": "vs" }, true);