location.href

js中location.href的用法有哪些

小亿
113
2023-07-07 09:56:54
栏目: 编程语言

在JavaScript中,location.href是一个属性,用于获取或设置当前页面的URL。它有以下用法:

  1. 获取当前页面的URL:
var url = location.href;
console.log(url);
  1. 设置当前页面的URL:
location.href = "http://example.com";
  1. 使用相对路径设置当前页面的URL:
location.href = "/path/to/page.html";
  1. 使用hash设置当前页面的URL:
location.href = "#section1";
  1. 使用查询参数设置当前页面的URL:
location.href = "?key=value";
  1. 使用hash和查询参数设置当前页面的URL:
location.href = "#section1?key=value";
  1. 将当前页面重定向到另一个URL:
location.href = "http://example.com";

请注意,使用location.href设置URL会导致页面的重加载。

0
看了该问题的人还看了