location怎么用,window.location的对象属性用法
`window.location`对象包含有关当前文档位置的信息并允许您与浏览器进行导航。它具有以下属性:
- `window.location.href`:包含完整的URL,可以读取或设置该属性来导航到新的URL。
- `window.location.protocol`:包含当前URL的协议部分(例如`http:`、`https:`)。
- `window.location.host`:包含当前URL的主机名称和端口号。
- `window.location.hostname`:包含当前URL的主机名称。
- `window.location.port`:包含当前URL的端口号。
- `window.location.pathname`:包含当前URL的路径部分。
- `window.location.search`:包含当前URL的查询字符串部分(即URL中位于问号后面的部分)。
- `window.location.hash`:包含当前URL的锚点部分(即URL中位于井号后面的部分)。
例如,如果当前URL是`https://example.com/path?id=123#section`,则可以通过以下方式访问这些属性:
console.log(window.location.href); // https://example.com/path?id=123#section console.log(window.location.protocol); // https: console.log(window.location.host); // example.com console.log(window.location.hostname); // example.com console.log(window.location.port); // (空字符串) console.log(window.location.pathname); // /path console.log(window.location.search); // ?id=123 console.log(window.location.hash); // #section
这些属性可以帮助您在JavaScript中操作URL的各个部分。
THE END
二维码
打赏

共有 0 条评论