location是最有用的BOM对象之一,它提供了与当前窗口中加载的文档有关的信息,还提供了一些导航功能。事实上,location对象是一个很特别的对象,因为它既是window对象的属性,也是document对象的属性;换句话说,window.location和document.location引用的是同一个对象。
console.log(location.hash);//返回URL中的hash(#号后跟零或多个字符),如果URL中不包含散列,则返回空字符串
console.log(location.host);//返回服务器名称和端口号(如果有)
console.log(location.href);//返回当前加载页面的完整URL。而location对象的toString()方法也返回这个值
console.log(location.hostname)//返回不带端口号的服务器名称
console.log(location.pathname);//返回URL中的目录和(或)文件名
console.log(location.port);//返回URL中指定的端口号。如果URL中不包含端口号,则这个属性返回空字符串
console.log(location.protocol)//;返回页面使用的协议。通常是http:或https:
console.log(location.search);//返回URL测查询字符串。这个字符串以问好开头
console.log(location);
//位置操作
/*可以使用上述的每一个location来改变location的当前属性的值*/
// location.hash = "#section";
location.href = "http://www.baidu.com";//改变浏览器位置最常用的方法
window.location = "http://www.baidu.com";
location.assign("http://www.baidu.com");//上面两种方式是隐式调用assign方法
location.reload()//重新加载(有可能从缓存中加载)
location.reload(true);//重新加载,(从服务器重新加载)
//查询字符串参数
function getQueryStringArgs(){
var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
args = {},
items = qs.length ? qs.split("&") : [],
item = null,
name = null,
value = null,
i = 0,
len = items.length;
for(i = 0;i<len;i++){
item = items[i].split("=");
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if(name.length){
args[name] = value;
}
}
return args;
}
setTimeout(function () {
location.replace("http://www.baidu.com");//replace禁用返回(回退)按钮,不会生成原网页的历史记录
},1000);