题目描述:
获取 url 中的参数
- 指定参数名称,返回该参数的值 或者 空字符串
- 不指定参数名称,返回全部的参数对象 或者 {}
- 如果存在多个同名参数,则返回数组
输入描述:http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe key
输出描述:[1,2,3]
function getUrlParam(sUrl, sKey) {
let sParam = sUrl.split("?")[1].split("#")[0]; //key=1&key=2&key=3&test=4
let arr = sParam.split("&"); //["key=1","key=2","key=3","test=4"]
let res;
if( sKey ){//如果指定参数
res = [];
for( let i = 0; i < arr.length; i++ ){
var temp = arr[i].split("=");
if( temp[0] === sKey ){
res.push( temp[1] ); //res只存储指定key值的结果
}
}
if( res.length == 1 ){
return res[0];
}else if( res.length == 0 ){
return "";
}else{
return res;
}
}
else{//如果不指定参数
res = {};
if( sParam==undefined || sParam=="" ){
return res;
}
for( let i = 0; i < arr.length; i++ ){
var temp = arr[i].split("=");
if( !(temp[0] in res) ){
res[temp[0]] = []; //temp[0]为键,temp[1]的数组为值
}
res[temp[0]].push(temp[1]); //使用变量动态访问对象属性用obj[a]不能用obj.a
}
}
return res;
}
补充location对象:
是最有用的BOM 对象之一,既是window对象的属性又是document对象的属性,提供了当前窗口中加载的文档有关的信息,还提供了一些导航功能。
-
常用的属性与方法:
location.href:完整url
location.hash:hash值(#hash)
location.search:参数(?q=js)
location.assign(newurl):url跳转 等同于window.href=newurl/location.href=newurl;
location.reload():重新加载 如果没有参数会以最有效的方式重新加载,即页面自上次请求没有发生变化会从浏览器缓存中加载,如果参数是true,会强制从服务器重新加载。 -
不常用:
location.host:服务器名与端口号(www.wrox.com:80)
location.hostname:服务器名(www.wrox.com)
location.port:端口号(8080)
location.pathname:目录和文件名(/js/test.html)
location.protocol:协议(http)
location.replace():url跳转 但是使用后退按钮不能回到上一个页面