【作用】
提供了与当前窗口中加载的文档有关的信息,可以将URL解析为独立的片段,以及一些导航功能。
【特殊性】
location既是window对象的属性,亦是document对象的属性。
location既是window对象的属性,亦是document对象的属性。
【location对象的所有属性】
属性名 | 例子 | 说明 |
hash | '#contents' | 返回URL中的hash(#号后跟零或多个字符),如果URL中不包含散列,则返回空字符串 |
host | 'www.wrox.com:80' | 返回服务器名称和端口号(如果有) |
hostname | 'www.wrox.com' | 返回服务器名称 |
href | 'http:/www.wrox.com' | 返回完整路径 |
pathname | '/mulu/' | 返回URL中的目录和(或)文件名 |
port | '80' | 返回URL中指定的端口。如果不包含端口,则这个属性返回空字符串 |
protocol | 'http:' | 返回页面使用的协议 |
search
|
'?q=javascript'
|
返回URL的查询字符串。这个字符串以问号开头
|
![](https://i-blog.csdnimg.cn/blog_migrate/637856fc83babd09f5962514086eec4f.png)
【示例】
location.hash
"#bkmk_clientsideJS"
location.host
"msdn.microsoft.com"
location.hostname
"msdn.microsoft.com"
location.href
"https://msdn.microsoft.com/zh-cn/library/gg334279.aspx#bkmk_clientsideJS"
location.pathname
"/zh-cn/library/gg334279.aspx"
location.port
""
location.protocol
"https:"
location.search
""
![](https://i-blog.csdnimg.cn/blog_migrate/b8307397b8e54aaf83a70835450062a9.png)
【查询字符串参数】
location.search返回从问号到URL末尾的所有内容,但却没有办法逐个访问其中的每个查询字符串参数。因此,我们可以创建一个函数,用以解析查询字符串,然后返回所有参数的一个对象。
<script type="text/javascript">
function getQueryStringArgs() {
//取得查询字符串并去掉开头的问号
var queryString = (location.search.length > 0 ? location.search.substring(1) : '');
//保存数据的对象
var args = {};
//取得每一项
var items = queryString.length > 0 ? queryString.split('&') : [];
var item = null;
var name = null;
var value = null;
//逐个将每一项添加到args对象中
for (var i = 0; i < items.length; i++) {
item = items[i].split('=');
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if (name.length > 0) {
args[name] = value;
}
}
return args;
}
</script>
【位置操作】
方法:location.assign();
参数:传递一个URL
参数:传递一个URL
方法:location.reload();
作用:重新加载当前页面
注意:如果不传参数,有可能是从缓存中加载,如果传入参数true,则从服务器重新加载
一般,重新导航到一个新的页面时,用户点击后退是可以回到前一个页面,接下的方面却不能
方法:location.replace('URL');