文章摘要
这篇文章介绍了如何使用JavaScript获取和修改浏览器当前页面的位置信息。通过`window.location`属性和相关方法,可以获取或设置以下信息:
1. `hash`:获取URL的查询部分。
2. `host`和`hostname`:获取当前页面的域名。
3. `pathname`:获取文件路径。
4. `port`:获取端口号。
5. `protocol`:获取协议(如HTTP)。
6. `search`:获取搜索参数。
此外,文章还介绍了如何通过`location.href`、`location.assign`和`location.reload`方法进行页面重定向,以及如何使用`location.replace`清除历史记录。这些功能是开发者在处理动态网页和浏览器行为时常用的工具。
//地址栏上#及后面的内容
console.log(window.location.hash);
//主机名及端口号
console.log(window.location.host);
//主机名
console.log(window.location.hostname);
//文件的路径—相对路径
console.log(window.location.pathname);
//端口号
console.log(window.location.port);
//协议
console.log(window.location.protocol);
//搜索的内容
console.log(window.location.search);
//设置跳转的页面的地址
location.href=”http://www.jb51.net”;//属性—————–>必须记住
location.assign(“http://www.jb51.net”);//方法
//重新加载–刷新
location.reload();
//没有历史记录
location.replace(“http://www.jb51.net”);
console.log(window.location.hash);
//主机名及端口号
console.log(window.location.host);
//主机名
console.log(window.location.hostname);
//文件的路径—相对路径
console.log(window.location.pathname);
//端口号
console.log(window.location.port);
//协议
console.log(window.location.protocol);
//搜索的内容
console.log(window.location.search);
//设置跳转的页面的地址
location.href=”http://www.jb51.net”;//属性—————–>必须记住
location.assign(“http://www.jb51.net”);//方法
//重新加载–刷新
location.reload();
//没有历史记录
location.replace(“http://www.jb51.net”);
© 版权声明
文章版权归作者所有,未经允许请勿转载。