Location对象
location特性:既是window对象的属性,也是document对象的属性,window.location和document.location引用的是同一个对象。作用:①保存当前文档的信息;②提供导航功能;③将URL解析为独立的片段。
1.location的属性
//location对象的属性:
//锚
console.log(location.hash);
//服务器名称和端口号
console.log(location.host);
//服务器名称
console.log(location.hostname);
//端口号
console.log(location.port);
//完整的URL
console.log(location.href);
//目录和文件名
console.log(location.pathname);
//页面使用的协议
console.log(location.protocol);
//查询字符串
console.log(location.search);
2.查询字符串参数
//查询字符串参数的函数:
function getQueryStringArgs() {
var qs = location.search.length > 0 ? location.search.substring(1):"";
var args = {},items = qs.length?qs.split("&"):[],item=null,name=null,value=null,
i=0,len=items.length;
for(;i<len;i++){
item = items[i].split("=");
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if(name.length){
args[name] = value;
}
}
return args;
}
console.log(getQueryStringArgs());
3.location的导航
//location的导航
//改变location的大部分属性都会引起页面的重新加载,包括href,host,hostname,port,search,不包括hash,修改hash不会重新加载页面
document.getElementsByClassName('skip-btn')[0].onclick = function () {
//这3句代码的效果是一致的:都会产生一条历史记录,到新页面之后用户可以后退
location.href = 'https://baidu.com';
location.assign('https://baidu.com');
window.location = 'https://baidu.com';
//如果想替换当前URL:
location.replace('https://baidu.com');
//重新刷新当前页面:
//可能会从浏览器缓存中加载页面:
location.reload();
//强制从服务器重新加载页面:
location.reload(true);
}
网友评论