BOM
5 location对象
案例:五秒钟之后自动跳转页面
案例分析
- 利用定时器做倒计时效果
- 时间到了就跳转页面。使用location.href
17-五秒钟之后跳转页面.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>点击</button>
<div></div>
<script>
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.addEventListener('click', function() {
// console.log(location.href); // 点击按钮之后在控制台拿到地址
// 想点击完之后去往一个新地址
location.href = 'http://www.itcast.cn';
})
var timer = 5;
setInterval(function() {
if(timer == 0) {
location.href = 'http://www.itcast.cn';
} else {
div.innerHTML = '您将在'+ timer +'秒钟之后跳转到首页';
timer --;
}
}, 1000)
</script>
</body>
</html>
效果
案例:获取URL地址
主要练习数据在不同页面中的传递。
案例分析
- 第一个登录页面,里面有提交表单, action提交到index.html页面
- 第二个页面,可以使用第一个页面的参数,这样实现了一个数据不同页面之间的传递效果
- 第二个页面之所以可以使用第一个页面的数据,是利用了URL里面的location.search参数
- 在第二个页面中,需要把这个参数提取。
- 第一步去掉?利用substr
- 第二步利用=号分割键 和 值 split(’ = ')
18-获取URL参数
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="index.html">
用户名:<input type="text" name="uname"> <!--这个表单里面的name 一定不能不写-->
<input type="submit" value="登录">
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div></div>
<script>
console.log(location.search); // ?uname=andy
// 1 先去掉 ? substr('起始的位置',截取几个字符)
var params = location.search.substr(1,); // uname=andy
console.log(params);
// 2 利用 = 把字符串分割为数组 split('=');
var arr = params.split('=')
console.log(arr); // ['uname', 'andy']
var div = document.querySelector('div');
// 3 把数据写入div中
div.innerHTML = arr[1] + '欢迎你';
</script>
</body>
</html>
效果
注意变化:
输入用户名,点击登录之后
5.4 location 对象的方法
location对象方法 | 返回值 |
---|---|
location.assign() | 跟href 一样,可以跳转页面(也称为重定向页面) |
location.replace() | 替换当前页面,因为不记录历史,所以不能后退页面 |
location.reload() | 重新加载页面,相当于刷新按钮或者f5如果参数为true强制刷新ctrl+f5 |