Location 对象
一.什么是location对象
window对象给我们提供了一个location属性用于获取或设置窗体的URL,并且可以用于解析URL。因为这个属性返回的是一个对象,所以我们将这个属性也称为location对象。
1.url
统一资源定位符(Uniform Resource Locator, URL)是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么熔理它。
Location 对象属性
属性 | 描述 |
---|---|
hash | 返回一个URL的锚部分 |
host | 返回一个URL的主机名和端口 |
hostname | 返回URL的主机名 |
href | 返回完整的URL |
pathname | 返回的URL路径名。 |
port | 返回一个URL服务器使用的端口号 |
protocol | 返回一个URL协议 |
search | 返回一个URL的查询部分 #后面内容 常见于链接 锚点 |
举个栗子:
href
<button>点击</button>
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function () {
console.log(location.href); //
})
</script>
二.5秒钟之后跳转页面的小案例
<!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');
var time = 5;
btn.addEventListener('click', function () {
// console.log(location.href); //有中文的话会出现乱码
location.href = 'http://www.baidu.com'
})
countDown();
setInterval(countDown, 1000);
function countDown() {
if (time == 0) {
location.href = 'http://www.baidu.com';
} else {
div.innerHTML = '您将在' + time + '秒钟后跳转页面'
time--;
}
}
</script>
</body>
</html>
效果如下:
三.获取URL参数传递
主要练习数据在不同页面中的传递
代码思路:
- 第一个登录页面,里面有提交表单,action提交到index.html页面
- 第二个页面,可以使用第一个页面的参数,这样实现了一个数据不同页面之间的传递效果
- 第二个页面之所以可以使用第一个页面的数据,是利用了URL里面的location.search参数
- 在第二个页面中,需要把这个参数提取
第一步去掉?利用substr('起始的位置',截取几个字符)
第二步利用=号分割键和值split('=')
需要设置两个页面
第一个登录页面
<style>
input {
outline: none;
}
</style>
</head>
<body>
<form action="index.html">
用户名: <input type="text" name="uname">
<input type="submit" value="登录">
</form>
第二个登录进去的首页界面
<style>
span {
color: pink;
}
</style>
</head>
<body>
<div></div>
</body>
<script>
console.log(location.search); //?uname=
// 第一步去掉?利用substr('起始的位置',截取几个字符)
// 第二步利用=号分割键和值split('=')
var params = location.search.substr(1);
var arr = params.split('=');
console.log(arr); //数组
var div = document.querySelector('div');
// 把数据写在div中
var text = arr[1];
// text.style.fontColor = 'pink';
div.innerHTML = `<span>${text}</span> , 欢迎您`;
</script>
效果如下:
Location 对象方法
方法 | 说明 |
---|---|
assign() | 载入一个新的文档,跟href一样,可以跳转页面(也称为重定向页面) |
reload() | 重新载入当前文档 相当于刷新按钮 |
replace() | 用新的文档替换当前文档 因为不记录历史,所以不能后退页面 |
示例如下:
<button>点击</button>
<script>
let btn = document.querySelector('button');
btn.addEventListener('click', function () {
//记录浏览历史,可以实现后退功能
location.assign('http://www.baidu.com');
//不记录浏览历史,不可以实现后退功能
// location.replace('http://www.baidu.com');
//重新加载页面
// location.reload();
})
</script>