JS Window Location
声明
该文部分代码和内容节选自菜鸟教程,仅用作个人学习,特此声明
JS Window Location
window.location
对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面
1、Window Location
window.location 对象在编写时可不使用 window 这个前缀。
Window.Location的一些属性:
location.hostname
返回 web 主机的域名location.pathname
返回当前页面的路径和文件名location.port
返回 web 主机的端口 (80 或 443)location.protocol
返回所使用的 web 协议(http: 或 https:)
2、Location Href
location.href
属性返回当前页面的整个 URL。
document.write(location.href);//https://www.runoob.com/js/js-window-location.html
3、Location Pathname
location.pathname
属性返回 URL 的路径名。
document.write(location.pathname);///js/js-window-location.html
4、Assign 和 Replace
-
location.assign()
方法加载新的文档。<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>location.assign()</title> <script> function newDoc(){ window.location.assign("http://www.hao123.com") } </script> </head> <body> <input type="button" value="加载新文档" onclick="newDoc()"> </body> </html>
-
location.replace()
方法将当前文档替换为新的文档<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>location.replace()</title> <script> function newDoc(){ window.location.replace("http://www.hao123.com") } </script> </head> <body> <input type="button" value="加载新文档" onclick="newDoc()"> </body> </html>
-
二者的区别
replace()
从文档历史记录中删除当前 URL。- 使用
replace()
时,无法使用 “后退” 导航回原始文档。