网站首页 > 教程文章 正文
8.2 location对象
window.location与document.location都可以访问,是指向的同一对象。下面是location的属性的示例:
// 以下都以此url为例:https://www.baidu.com:80/index.html?rn=24&pn=1#home
// 返回url地址中#部分的字符
alert(location.hash); // home
// 返回服务器名称和端口号
alert(location.host); // www.baidu.com:80
// 返回服务器名称,不带端口号
alert(location.hostname); // www.baidu.com
// 返回当前加载页面的完整url,同toString()方法
alert(location.href); // https://www.baidu.com
// 返回url中的目录和文件名
alert(location.pathname); // index.html
// 返回url中的端口号
alert(location.port); // 80
// 返回页面使用的协议 http,https,ftp
alert(location.protocol); // https
// 返回URL的查询字符串,以?开头
alert(location.search); // ?rn=24&pn=1
8.2.1 查询字符串参数
search属性可以拿到所有查询字符串,不过是整个字符串,可以通过以下的函数来返回一个字典对象。
// 返回查询字符串
function getQueryStringArgs(){
var qs = (location.search.length > 0 ? location.search.substring(1) : "");
var args = {};
var items = qs.length ? qs.split("&") : [];
var item = null;
var name = null;
var value = null;
for (var i = 0;i < items.length;i++){
item = items[i].split("=");
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if (name.length){
args[name] = value;
}
}
return args;
}
8.2.2 位置操作
// 以下三种方式都可以打开新的url
location.assign(url);
window.location = url;
window.location.href = url;
// 以下面方式修改location属性的话,相应的url也会改变
location.pathname = newValue;
通过上述的方式改变url会在历史记录里生成新的记录,可以使用后退按钮回到前一个页面,如果使用location.replace()方法则没有记录,会在1秒后重新定位到新的url。
window.location.replace(url);
// 重新加载,以最有效的方式加载(即没有更改的情况下,可能从缓存中加载)
window.location.reload();
// 重新加载,不管缓存中有不有,都从服务器中加载
window.location.reload(true);
猜你喜欢
- 2024-12-01 Shopify模版编辑器问题排查及解决办法汇总
- 2024-12-01 JS实现防止别人通过控制台调试网站
- 2024-12-01 Web安全防范知识基础讲解
- 2024-12-01 「Shopify」屏蔽国内同行卖家访问网站
- 2024-12-01 避免网站中出现 index.html
- 2024-12-01 实现网页跳转的方法
- 2024-12-01 将 Safari 打造成 iOS 里的快速启动中心:Bookmarklet
- 2024-12-01 JMeter主要组件介绍(一)
- 2024-12-01 H5浏览器直接调起微信(url协议 weixin:// )判断是否安装微信
- 2024-12-01 HTTP GET如何在分页查询时传递中文参数值
- 最近发表
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- md5 sha1 (32)
- mybatis plus page (35)
- semaphore 使用详解 (32)
- update from 语句 (32)
- vue @scroll (38)
- 堆栈区别 (33)
- 在线子域名爆破 (32)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)