一限番、正則表達(dá)式獲取地址欄參數(shù)(代碼簡(jiǎn)介舱污,重點(diǎn)正則)
let LocString = String(window.document.location.href);//URL地址
console.log(LocString, "LocString");
//獲取當(dāng)前url中的參數(shù)
function GetQueryString(name) {
let rs = new RegExp("(^|)" + name + "=([^&]*)(&|$)", "gi").exec(
LocString
),
tmp;
if ((tmp = rs)) return tmp[2];
return null;
}
調(diào)用方法
let 參數(shù)1 = GetQueryString("參數(shù)名1"));
let outcabID = GetQueryString("id"); //獲取url的id
let ConOrOper = decodeURI(GetQueryString("參數(shù)名稱(chēng)")); //獲取其他參數(shù)
二、split拆分(代碼較為復(fù)雜弥虐,交易理解)
function GetRequest() {
let url = location.search; //獲取url中"?"符后的字串
let theRequest = new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1);
strs = str.split("&");
for(let i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
調(diào)用方法
let Request = new Object();
Request = GetRequest();
let 參數(shù)1,參數(shù)2 ...;
參數(shù)1 = Request['參數(shù)1'];
參數(shù)2 = Request['參數(shù)2'];
參數(shù)... = Request['參數(shù)...'];
三扩灯、split拆分法(易于理解,代碼簡(jiǎn)易理解)
function getQueryVariable(variable){
let query = window.location.search.substring(1);
let vars = query.split("&");
for (let i=0;i<vars.length;i++) {
let pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
調(diào)用方法
let 參數(shù)1 = getQueryVariable("參數(shù)名1");
補(bǔ)充URL知識(shí):
示例url = http://www.reibang.com/search?q=js&page=1&type=note
1霜瘪、window.location.href(設(shè)置或獲取整個(gè) URL 為字符串)
console.log(window.location.href)
打印結(jié)果:`http://www.reibang.com/search?q=123&page=1&type=note`
2珠插、window.location.protocol(設(shè)置或獲取 URL 的協(xié)議部分)
console.log(window.location.protocol)
打印結(jié)果:`http:`
3、window.location.host(設(shè)置或獲取 URL 的主機(jī)部分)
console.log(window.location.host)
打印結(jié)果:`www.reibang.com`
4颖对、window.location.port(設(shè)置或獲取與 URL 關(guān)聯(lián)的端口號(hào)碼)
console.log(window.location.port)
打印結(jié)果:`空字符(如果采用默認(rèn)的80端口(update:即使添加了:80)捻撑,那么返回值并不是默認(rèn)的80而是空字符)`
5、window.location.pathname(設(shè)置或獲取與 URL 的路徑部分(就是文件地址))
console.log(window.location.pathname)
打印結(jié)果:`/search`
6缤底、window.location.search(設(shè)置或獲取 href 屬性中跟在問(wèn)號(hào)后面的部分)【面試中常見(jiàn)】
console.log(window.location.search)
打印結(jié)果:`?q=123&page=1&type=note`
**PS:獲得查詢(xún)(參數(shù))部分顾患,除了給動(dòng)態(tài)語(yǔ)言賦值以外,我們同樣可以給靜態(tài)頁(yè)面个唧,并使用javascript來(lái)獲得相信應(yīng)的參數(shù)值江解。**
7、window.location.hash(設(shè)置或獲取 href 屬性中在井號(hào)“#”后面的分段)
console.log(window.location.hash)
打印結(jié)果:`空字符(因?yàn)閡rl中沒(méi)有)`