一、location是什么
JavaScript中的location对象代表了当前窗口的URL。它用于获取或设置当前页面URL。可以通过window.location或location来访问location对象。
二、location常用的属性
1. href
href属性是一个字符串,用于获取或设置当前窗口的URL。设置href属性可以让当前页面跳转到新的URL。
// 获取当前窗口的URL
let currentUrl = window.location.href;
console.log(currentUrl);
// 跳转到新的URL
window.location.href = "http://www.example.com";
2. origin
origin属性返回当前页面的协议,主机名和端口号。与href不同的是,它不包含路径和查询参数。
// 获取当前页面的协议,主机名和端口号
let currentOrigin = window.location.origin;
console.log(currentOrigin);
3. protocol
protocol属性返回当前页面的协议(如http:、https:等)。
// 获取当前页面的协议
let currentProtocol = window.location.protocol;
console.log(currentProtocol);
4. host
host属性返回当前页面的主机名和端口号。
// 获取当前页面的主机名和端口号
let currentHost = window.location.host;
console.log(currentHost);
5. hostname
hostname属性返回当前页面的主机名。
// 获取当前页面的主机名
let currentHostname = window.location.hostname;
console.log(currentHostname);
6. port
port属性返回当前页面使用的端口号。
// 获取当前页面使用的端口号
let currentPort = window.location.port;
console.log(currentPort);
7. pathname
pathname属性返回当前页面的路径部分(即主机名后面的部分,不包含查询参数和锚点)。
// 获取当前页面的路径部分
let currentPathname = window.location.pathname;
console.log(currentPathname);
8. search
search属性返回查询参数部分(即URL中问号后面的部分)。
// 获取当前页面的查询参数部分
let currentSearch = window.location.search;
console.log(currentSearch);
9. hash
hash属性返回锚点部分(即URL中#号后面的部分)。
// 获取当前页面的锚点部分
let currentHash = window.location.hash;
console.log(currentHash);
三、location常用的方法
1. assign()
assign()方法用于将当前窗口跳转到一个新的URL。
// 跳转到新的URL
window.location.assign("http://www.example.com");
2. replace()
replace()方法与assign()方法类似,也用于将当前窗口跳转到一个新的URL。但它不会在浏览器的历史记录中添加一个新的记录。
// 跳转到新的URL,但不在浏览器历史记录中添加新记录
window.location.replace("http://www.example.com");
3. reload()
reload()方法用于重新加载当前页面。它可以接受一个布尔值参数,指示是否清除缓存重新加载。
// 重新加载当前页面
window.location.reload();
// 清除缓存并重新加载当前页面
window.location.reload(true);
四、小结
location对象在JavaScript中扮演着重要的角色,它可以用于获取或设置当前页面的URL。我们可以使用location的属性和方法来完成页面跳转、获取URL的各个部分等操作。
原创文章,作者:OJLJB,如若转载,请注明出处:https://www.506064.com/n/332912.html