什么是 location 对象
window 对象给我们提供了一个 location 属性用于获取或设置窗体的 URL,并且可以用于解析 URL 。 因为 这个属性返回的是一个对象,所以我们将这个属性也称为 location 对象
URL
统一资源定位符 (Uniform Resource Locator, URL) 是互联网上标准资源的地址。互联网上的每个文件都有 一个唯一的 URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。
protocol://host[:port]/path/[?query]#fragment
http://www.itcast.cn/index.html?name=andy&age=18#link
重点记住: href 和 search
5秒之后跳转页面
案例分析
① 利用定时器做倒计时效果 ② 时间到了,就跳转页面。 使用 location.href
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>点击</button>
<div></div>
<script>
var btn=document.querySelector('button')
var div=document.querySelector('div')
btn.addEventListener('click',function(){
location.href='http://www.baidu.com';
})
var timer=5;
time();
setInterval(time,1000);
function time(){
if(timer==0){
location.href='http://www.baidu.com';
}else{
div.innerHTML=`你将在${timer}之后跳转页面`;
timer--;
}
}
</script>
</body>
</html>
案例: 获取 URL 参数
主要练习数据在不同页面中的传递。
案例分析
① 第一个登录页面,里面有提交表单, action 提交到 index.html页面
② 第二个页面,可以使用第一个页面的参数,这样实现了一个数据不同页面之间的传递效果
③ 第二个页面之所以可以使用第一个页面的数据,是利用了URL 里面的 location.search参数
④ 在第二个页面中,需要把这个参数提取。
⑤ 第一步去掉? 利用 substr
⑥ 第二步 利用=号分割 键 和 值 split(‘=‘)
⑦ 第一个数组就是键 第二个数组
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="index.html">
<!-- 表单要有表单域才能提交 -->
用户名:<input type="text" name="uname"/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div></div>
<script>
// console.log(location.search)//?uname=1111
// 1.先去掉? substr('起始的位置',截取几个字符)
var params=location.search.substr(1);//uname=1111
// console.log(params)
// 2.利用=把字符串分割为数组 split('=')
var arr=params.split('=');
// console.log(arr) (2) ['uname', '1111']0: "uname"1: "1111"length: 2[[Prototype]]: Array(0)
var div=document.querySelector('div')
// 把数据写入div中
div.innerHTML=arr[1]+"欢迎你";
</script>
</body>
</html>
location常见方法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>点击</button>
<script>
var btn=document.querySelector('button')
btn.addEventListener('click',function(){
// 记录浏览历史,所以可以实现后退功能
// location.assign('https://www.baidu.com')
// 不记录浏览历史,所以不可以实现后退功能
// location.replace('https://www.baidu.com')
// 类似于浏览器中的刷新 没有参数就是刷新 参数为true就是强制刷新 把缓存也刷了
location.reload(true)
})
</script>
</body>
</html>
本文含有隐藏内容,请 开通VIP 后查看