window.location用法总结及注意事项

it2024-08-03  42

window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。在编写时可不使用 window 这个前缀。 例如:当前网https://www.runoob.com/js/js-window-location.html location.href 属性返回当前页面的 URL。

<script> document.write(location.href); </script>

输出为:

https://www.runoob.com/js/js-window-location.html

location.pathname 属性返回 URL 的路径名。

<script> document.write(location.pathname); </script>

输出为:

/js/js-window-location.html

location.hostname 返回 web 主机的域名 location.port 返回 web 主机的端口 (80 或 443) location.protocol 返回所使用的 web 协议(http: 或 https:) location.assign() 方法加载新的文档。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <head> <script> function newDoc(){ window.location.assign("https://www.runoob.com") } </script> </head> <body> <input type="button" value="加载新文档" onclick="newDoc()"> </body> </html>

注意

window.location.assign(url) : 加载 URL 指定的新的 HTML 文档。 就相当于一个链接,跳转到指定的url,当前页面会转为新页面内容,可以点击后退返回上一个页面。

window.location.replace(url) : 通过加载 URL 指定的文档来替换当前文档 ,这个方法是替换当前窗口页面,前后两个页面共用一个窗口,所以是没有后退返回上一页的

最新回复(0)