介绍
location对象属于window对象,拆分并保存了URL地址的各个组成部分,写的时候可以省略window。
location对象常用属性和方法:
- href 属性:获取完整的 URL 地址,对其赋值时用于地址的跳转。
- search属性:属性获取地址中携带的参数,符号 ?后面部分。
- hash 属性:获取地址中的啥希值,符号 # 后面部分
- reload 方法:用来刷新当前页面,传入参数 true 时表示强制刷新
示例
示例:window.location和location是同一个对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(window.location)
console.log(location)
</script>
</body>
</html>
示例:打印location对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(location)
</script>
</body>
</html>
示例:打印location对象的href属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(location.href)
</script>
</body>
</html>
利用location对象的href属性实现跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 经常用href,利用js的方式跳转页面
location.href = 'http://www.baidu.com'
</script>
</body>
</html>
显示location的search属性
示例:获得location对象的hash属性
示例:调用location对象的reload()方法进行刷新
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="username">
<input type="password" name="pwd">
<button>提交</button>
</form>
<a href="#/my">我的</a>
<a href="#/friend">关注</a>
<a href="#/download">下载</a>
<button class="reload">刷新</button>
<script>
const reload = document.querySelector('.reload')
reload.addEventListener('click', function () {
// 相等于在页面中按下了F5来刷新页面
// location.reload()
// 强制刷新,相当于Ctrl+F5
location.reload(true)
})
</script>
</body>
</html>