JavaScript编程中window的location与history对象详解
WindowLocation
- window.location对象用于获得当前页面的地址(URL),并把浏览器重定向到新的页面。
- window.location对象在编写时可不使用window这个前缀。一些例子:
- 一些实例:
- location.hostname返回web主机的域名
- location.pathname返回当前页面的路径和文件名
- location.port返回web主机的端口(80或443)
- location.protocol返回所使用的web协议(http://或https://)
WindowLocationHref
location.href属性返回当前页面的URL。
实例
返回(当前页面的)整个URL:
<script> document.write(location.href); </script>
WindowLocationPathname
location.pathname属性返回URL的路径名。
实例
返回当前URL的路径名:
<script> document.write(location.pathname); </script>
以上代码输出为:
/js/js-window-location.html
WindowLocationAssign
location.assign()方法加载新的文档。
实例
加载一个新的文档:
<html> <head> <script> functionnewDoc() { window.location.assign("http://www.w3cschool.cc") } </script> </head> <body> <inputtype="button"value="Loadnewdocument"onclick="newDoc()"> </body> </html>
WindowHistory
window.history对象在编写时可不使用window这个前缀。
为了保护用户隐私,对JavaScript访问该对象的方法做出了限制。
一些方法:
- history.back()-与在浏览器点击后退按钮相同
- history.forward()-与在浏览器中点击按钮向前相同
WindowHistoryBack
history.back()方法加载历史列表中的前一个URL。
这与在浏览器中点击后退按钮是相同的:
实例
在页面上创建后退按钮:
<html> <head> <script> functiongoBack() { window.history.back() } </script> </head> <body> <inputtype="button"value="Back"onclick="goBack()"> </body> </html>
WindowHistoryForward
historyforward()方法加载历史列表中的下一个URL。
这与在浏览器中点击前进按钮是相同的:
实例
在页面上创建一个向前的按钮:
<html> <head> <script> functiongoForward() { window.history.forward() } </script> </head> <body> <inputtype="button"value="Forward"onclick="goForward()"> </body> </html>