Location对象
window对象给我们提供了一个location属性用于获取或设置窗体的URL ,并且可以用于解析URL。因为这个属性返回的是一个对象,所以我们将这个属性也称为location对象。
URL
统一资源定位符(Uniform Resource Locator, URL)是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL ,它包含的信息指出文件的位置以及浏览器应该怎么处理它。
URL的一般语法格式为:
protocol://host [:port]/path/ [?query]# fragment
http: //www. itcast .cn/ index. html ?name =andysage=18#link
组成 | 说明 |
---|---|
protocol | 通信协议,常用的http,ftp,maito等 |
host | 主机(域名) www.theima.com |
port | 端口号可选,省略时使用方案的默认端口如http的默认端口为80 |
path | 路径由零或多个/符号隔开的字符串,-一般用来表示主机上的一个目录或文件地址 |
location对象属性
location对象属性 | 返回值 |
---|---|
location.href | 获取或者设置整个URL |
location. host | 返回主机(域名)www.itheima.com |
location.port | 返回端口号如果未写返回空字符串 |
location.pathname | 返回路径 |
location. search | 返回参数 |
location. hash | 返回片段#后面内容常见于链接锚点 |
location对象的方法
location对象的方法 | 返回值 |
---|---|
location.assign() | 跟href一样,可以跳转页面(也称为重定向页面) |
location.replace() | 替换当前页面,因为不记录历史,所以不能后退页面 |
location.reload() | 重新加载页面,相当于刷新按钮或者f5如果参数为true强制刷新ctrl+f5 |
navigator对象
navigator对象包含有关浏览器的信息,它有很多属性,我们最常用的是userAgent ,该属性可以返回由客户机发送服务器的user-agent头部的值。
//下面前端代码可以判断用户那个终端打开页面,实现跳转
if ((navigator userAgent.match (/(phone|pa|pod|iPhone|iPodl|ios||iPad |Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|Webos|Symbian|windows Phone)/i))) {
window. location.href = ""; //手机
} else {
window. location.href = ""; //电脑
}
history对象
window对象给我们提供了-个history对象,与浏览器历史记录进行交互。该对象包含用户(在浏览器窗口中)访问过的URL。
history对象的方法 | 返回值 |
---|---|
back() | 可以后退功能 |
forward() | 前进功能 |
go(参数) | 前进后退功能参数如果是1前进1个页面如果是-1后退1个页面 |
获取URL参数练习数据在不同页面间传递
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>把输入的用户名提交到另一个页面</title>
</head>
<body>
<form action="index.html">
用户名: <input type="text" name="uname">
<input type="submit" value="登录">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>显示指定页面提供的用户名</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>