ps: 項(xiàng)目太忙贰您,忘記從哪搬來的了坏平,做個(gè)記錄收藏一下
- 主要方法代碼
// 核心代碼
// 獲取全部地址欄參數(shù)
function getUrlParams() {
var vars = {}
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m, key, value) {
vars[key] = value
}
)
return vars
}
// 獲取指定地址欄參數(shù)
function getUrlKey(name){
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
2.方法應(yīng)用代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>原生js獲取地址欄參數(shù)(全部和指定)</title>
<script type="text/javascript">
// 獲取全部地址欄參數(shù)
function getUrlParams() {
var vars = {}
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m, key, value) {
vars[key] = value
}
)
return vars
}
// 獲取指定參數(shù)
function getUrlKey(name){
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
window.onload = function(){
var urlParams = getUrlParams()
console.log(urlParams, '全部地址欄參數(shù)')
var name = getUrlKey('name')
console.log(name, '指定的name')
}
</script>
</head>
<body>
</body>
</html>
3.效果查看