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
location对象的属性
其中location.href的使用案例:
<html>
<head>
<meta charset="utf-8">
<title>333333</title>
<style>
</style>
</head>
<body>
<button>点击</button>
<div></div>
<script>
//点击按钮后开启倒计时,判断time为0时自动跳转页面
var btn = document.querySelector('button');
var div = document.querySelector('div');
var time = 5;
btn.addEventListener('click', function () {
div.innerHTML = '您将在'+time+'秒之后跳转页面';
setInterval(function () {
if(time <= 0) {
location.href = 'http://www.itcast.cn';
}else {
time--;
div.innerHTML = '您将在'+time+'秒之后跳转页面';
}
}, 1000)
})
</script>
</body>
</html>
获取URL参数数据
案例:
分析:
- 第一个登陆页面有提交表单,action提交到index.html页面
- 第二个页面可以使用第一个页面的参数,实现一个数据不同页面之间传递的效果
- 第二个页面之所以可以使用第一个页面的数据,是利用了url里面的location.search参数
- 在第二个页面中使用substr去掉"?"提取参数,利用"="分隔键和值 split('=');
代码
login.html
<!DOCTYPE html>
<html lang="Zh-CN">
<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>login</title>
</head>
<body>
<form action="index.html">
用户名<input type="text" name="uname">
<input type="submit" value="登录">
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="Zh-CN">
<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>index</title>
</head>
<body>
<div></div>
<script>
console.log(location.search);
//去掉"?" substr('起始的位置', 截取几个字符); params 参数
var params = location.search.substr(1);
console.log(params);
//利用"="把字符串分割为数组 split('=');
var arr = params.split('=');
name = arr[1];
//使用decodeURI()方法将url中转码的中文乱码转换回中文
name=decodeURI(name);
console.log(name);
var div = document.querySelector('div');
div.innerHTML = name + ' 欢迎您!';
</script>
</body>
</html>
location对象的方法
pc以及手机端跳转不同网址的代码案例:
if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMBErry|MQQBrowser|JUC|Fennec|wOSBeowser|BrowserNG|WebOs|Symbian|Windows Phone)/i))) {
window.location.href = '';//手机端网站
}else {
window.location.href = '';//电脑端网站
}