js 獲取地址欄參數的兩種方法以及window的一些常見用法

js 獲取地址欄參數的兩種方法

1. 傳統方法獲取:

function getParas(){
	var href = location.href.split("?")[1];
	var paras = href.includes("&") ? href.split("&") : href;
	//判斷是一組還是多組key:value
	var arr = [];
	for(var i=0;i<paras.length;i++){
		var item = paras[i].split("=");
		arr[item[0]] = item[1];
	}
	return arr;
}
getParas();
//[id: "13", name: "hah"]

2. 正則表達式獲取:

function getParas(pa){
	var reg = new RegExp("(^|&)" + pa + "=([^&]*)(&|$)");
	var r = location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}
getParas("id");
//"13"

window.location的一些常見屬性

示例url1:https://blog.csdn.net/?type=web
示例url2:https://blog.csdn.net/?#web

屬性 說明 示例
href 完整的url https://blog.csdn.net/?type=web
hash 從"#"開始的URL #web
search 從"?"開始的URL ?id=13&name=hah
host 主機名和當前URL的端口號 blog.csdn.net

window的一些常見方法

  • window.location.reload(); 強制刷新頁面,如有數據未提交,會提示是否提交
  • window.location.href = window.location.href; 刷新當前頁面
  • window.history.go(0); 刷新當前頁面
  • window.history.go(-1);返回上一個頁面
  • window.history.back();返回上一個頁面
  • window.open(" "); 在新窗口打開某個url
  • window.location.replace(" "); 將當前地址替換爲新地址(使用該方法後不能通過瀏覽器前進和後退箭頭來訪問已被替換的url)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章