JavaScript Location 对象
JavaScript Window Location 对象
Section titled “JavaScript Window Location 对象”window.location 对象提供了当前页面 URL 的信息,并允许你导航浏览器到新页面。
Window Location 对象
Section titled “Window Location 对象”window.location 对象可以直接通过 location 访问(因为在浏览器中 window 是全局对象)。
location 的关键属性包括:
location.href: 返回当前页面的完整 URL。location.hostname: 返回 Web 主机的域名。location.pathname: 返回当前页面的路径和文件名。location.protocol: 返回使用的 Web 协议(例如,"http:"或"https:")。location.search: 返回 URL 的查询字符串部分(例如,"?name=value")。location.hash: 返回 URL 的锚点部分(例如,"#section1")。
关键方法包括:
location.assign(url): 加载指定 URL 的新文档。location.replace(url): 用指定 URL 的新文档替换当前文档。当前页面不会保存在会话历史中,因此后退按钮不会导航到它。location.reload(): 重新加载当前页面。
Window Location href
Section titled “Window Location href”location.href 属性返回当前页面的完整 URL。你也可以为 location.href 分配一个新的 URL 以导航到新页面(类似于 location.assign())。
// Get the current URLconst currentUrl = window.location.href;document.getElementById("demo").textContent = `Page location is: ${currentUrl}`;
// Navigate to a new page// window.location.href = "https://www.example.com";Window Location hostname
Section titled “Window Location hostname”location.hostname 属性返回当前页面主机的域名。
const currentHostname = window.location.hostname;document.getElementById("demo").textContent = `Page hostname is: ${currentHostname}`;Window Location pathname
Section titled “Window Location pathname”location.pathname 属性返回当前页面在服务器上的路径。
const currentPathname = window.location.pathname;document.getElementById("demo").textContent = `Page path is: ${currentPathname}`;Window Location protocol
Section titled “Window Location protocol”location.protocol 属性返回页面的 Web 协议(例如,"http:" 或 "https:")。
const currentProtocol = window.location.protocol;document.getElementById("demo").textContent = `Page protocol is: ${currentProtocol}`;Window Location assign()
Section titled “Window Location assign()”location.assign() 方法加载一个新文档。这会在浏览器历史中创建一个条目,以便用户可以使用后退按钮。
function loadNewDocument() { window.location.assign("https://developer.mozilla.org");}
// HTML would have a button like:// <button onclick="loadNewDocument()">Load New Document</button>如果你不希望当前页面保存在浏览器历史中,请考虑使用 location.replace(url)。
处理查询参数
Section titled “处理查询参数”location.search 属性为你提供查询字符串(例如,?name=John&age=30)。为了方便地处理这些参数,你可以使用 URLSearchParams API:
// Assuming URL is: http://example.com/page?name=Alice&topic=JSconst queryParams = new URLSearchParams(window.location.search);
if (queryParams.has('name')) { const name = queryParams.get('name'); // "Alice" console.log(`Name from URL: ${name}`);}
if (queryParams.has('topic')) { const topic = queryParams.get('topic'); // "JS" console.log(`Topic from URL: ${topic}`);}URLSearchParams 提供了 get()、has()、set()、append() 和 delete() 等方法,用于轻松操作查询参数。你可以在 MDN Web Docs 上找到更多信息。