JavaScript Window Location
内容摘要
window.location 对象可用于获取当前页面地址(URL)并把浏览器重定向到新页面。
文章正文
window.location 对象可用于获取当前页面地址(URL)并把浏览器重定向到新页面。
大多数浏览器不会显示默认端口号(http 为 80,https 为 443)。
Window Location
window.location 对象可不带 window 前缀书写。
一些例子:
- window.location.href 返回当前页面的 href (URL)
- window.location.hostname 返回 web 主机的域名
- window.location.pathname 返回当前页面的路径或文件名
- window.location.protocol 返回使用的 web 协议(http: 或 https:)
- window.location.assign 加载新文档
Window Location Href
window.location.href 属性返回当前页面的 URL。
实例
显示当前页面的 href (URL):
1 2 | <span style= "font-size:14px;" >document.getElementById( "demo" ).innerHTML = "页面位置是 " + <code>window.location.href</code>; </span> |
结果是:
1 | <span style= "font-size:14px;" >页面位置是 http: //www.idcnote.com/js/js_window_location.asp</span> |
Window Location 主机名
window.location.hostname 属性返回(当前页面的)因特网主机的名称。
实例
显示主机的名称:
1 | document.getElementById( "demo" ).innerHTML = "页面主机名是 " + <code>window.location.hostname</code>; |
结果是:
1 | 页面主机名是 www.idcnote.com |
Window Location 路径名
window.location.pathname 属性返回当前页面的路径名。
实例
显示当前 URL 的路径名:
1 | document.getElementById( "demo" ).innerHTML = "页面路径是 " + <code>window.location.pathname</code>; |
结果是:
1 | <span style= "font-size:14px;" >页面路径是 /js/js_window_location.asp</span> |
Window Location 协议
window.location.protocol 属性返回页面的 web 协议。
实例
显示 web 协议:
1 | document.getElementById( "demo" ).innerHTML = "页面协议是 " + <code>window.location.protocol</code>; |
结果是:
1 | <span style= "font-size:14px;" >页面协议是 http:</span> |
Window Location 端口
window.location.port 属性返回(当前页面的)互联网主机端口的编号。
实例
显示主机的端口号:
1 | document.getElementById( "demo" ).innerHTML = "端口号是: " + window.location.port; |
大多数浏览器不会显示默认端口号(http 为 80,https 为 443)。
Window Location Assign
window.location.assign() 方法加载新文档。
实例
加载新文档:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <html> <head> <script> function newDoc() { window.location.assign( "https://www.idcnote.com" ) } </script> </head> <body> <input type= "button" value= "Load new document" onclick= "newDoc()" > </body> </html> |
代码注释