本篇使用 jQuery方法, 若覺得jQuery的方法很大包,可參考本站另一篇
javascript get query values from url 取網址參數
QueryString.js
把第一段的程式碼放到一個名叫 QueryString.js 的檔案,以後需要時再去引入這支檔案就可。
/*
VECTOR COOL
https://vector.cool
*/
(function($) {
$.QueryString = (function(paramsArray) {
let params = {};
for (let i = 0; i < paramsArray.length; ++i)
{
let param = paramsArray[i]
.split('=', 2);
if (param.length !== 2)
continue;
params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
}
return params;
})(window.location.search.substr(1).split('&'))
})(jQuery);
用法:
/*
VECTOR COOL
https://vector.cool
*/
//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"
//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }
//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object
//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue¶m2=val"
//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));
[……]
閱讀更多