一、location 对象是什么?
window 对象给我们提供了一个 location 属性用于获取或设置窗体的 url,并且可以用于解析 url 。 因为这个属性返回的是一个对象,所以我们将这个属性也称为 location 对象。
1.1 url
统一资源定位符 (uniform resource locator, url) 是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的 url,它包含的信息指出文件的位置以及浏览器应该怎么处理它。
url 的一般语法格式为:
protocol://host[:port]/path/[?query]#fragment http://www.itcast.cn/index.html?name=andy&age=18#link
二、 location 对象的属性
案例1:5秒钟之后自动跳转页面
分析:
利用定时器做倒计时效果 时间到了,就跳转页面。使用 location.href
<!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>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>
案例2:获取 url 参数数据(主要练习数据在不同页面中的传递)
分析:
- 第一个登录页面,里面有提交表单, action 提交到 index.html页面
- 第二个页面,可以使用第一个页面的参数,这样实现了一个数据不同页面之间的传递效果
- 第二个页面之所以可以使用第一个页面的数据,是利用了url 里面的 location.search参数
- 在第二个页面中,需要把这个参数提取。
- 第一步去掉? 利用 substr
- 第二步 利用=号分割 键 和 值 split(‘=‘)
- 第一个数组就是键 第二个数组就是值
三、location 对象的方法
<body> <button>点击</button> <script> var btn = document.queryselector('button'); btn.addeventlistener('click', function() { // 记录浏览历史,所以可以实现后退功能 // location.assign('http://www.itcast.cn'); // 不记录浏览历史,所以不可以实现后退功能 // location.replace('http://www.itcast.cn'); location.reload(true); }) </script> </body>
到此这篇关于bom中location对象的属性和方法的文章就介绍到这了,更多相关location对象的属性方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论