1.什么是location对象
location对象用于获取或设置窗体的URL,并且可以用于解析URL,返回的是一个对象
2.location对象的属性
location.href 获取或设置整个URL
location.host 返回主机(域名)
location.port 返回端口号 如果未写返回 空字符串
location.pathname 返回路径
location.search 返回参数
location.hash 返回片段 #后面内容
3.案例1:
点击按钮跳转页面
var btn=document.querySelector('button');
btn.addEventListener('click',function(){
location.href='https://www.baidu.com';
});
<button>跳到百度</button
案例2:
5秒之后自动跳转页面
var div=document.querySelector('div');
var time=5;
fn();
var timer=setInterval(fn,1000);
function fn(){
if(time==0){
clearInterval(timer);
location.href='https://www.baidu.com';
}else{
div.innerHTML='将在'+time+'秒之后跳转到百度';
time--;
}
}
<div></div>
案例3:
获取URL参数,在登录界面输入用户名密码进入index页面
思路:
①登录页面,里面有提交表单,action提交到index页面
②index页面,可以使用第一个页面的参数,实现数据在不同页面的传递效果
③在第二个页面使用location.cearch获取参数
④在第二个页面中提取参数,先去掉? (利用substr),然后利用=分割 split(’=’)
登录页面代码:
<form action="45.index.html">
用户名: <input type="text" name="uname">
<input type="submit" value="登录">
</form>
index页面代码
window.onload=function(){
//1.去掉?号
var params=location.search.substr(1);
//2.用=把字符串分割为数组
var arr=params.split('=');
var div=document.querySelector('div');
//3.把数组写进div
div.innerHTML=arr[1]+'欢迎您!';
}