资源描述
html window.location用法
window.location是 JavaScript 中的一个对象,它提供了当前窗口的 URL 地址信息,并且允许对窗口的 URL 进行修改,从而实现网页的跳转。
以下是window.location的常用方法:
1. window.location.href: 获取或设置整个 URL,等价于document.URL。
2. window.location.protocol: 获取 URL 的协议,等价于document.URLProtocol。
3. window.location.host: 获取 URL 的主机名和端口号,等价于document.URLHostName。
4. window.location.hostname: 获取 URL 的主机名,等价于document.URLHost。
5. window.location.port: 获取 URL 的端口号,等价于document.URLPort。
6. window.location.pathname: 获取 URL 的路径名,等价于document.URLPathName。
7. window.location.search: 获取 URL 的查询字符串,等价于document.URLQueryString。
8. window.location.hash: 获取 URL 的锚点(即 # 开头的部分),等价于document.URLAnchor。
下面是一些使用示例:
// 获取当前页面的完整 URL
var fullUrl = window.location.href;
console.log(fullUrl);
// 将页面跳转到新的 URL
window.location.href = "";
// 或者使用相对路径
window.location.href = "/path/to/page";
除了href属性之外,还可以使用window.location对象的其他属性来修改 URL 的不同部分,从而实现更为精细的页面跳转或重定向操作。
展开阅读全文