js的location对象(BOM 2)
location对象
location对象是BOM对象,提供有关当前窗口加载文档的有关信息,和一些导航功能还有可以将URL解析为独立片段。location既是window对象属性,也是document对象属性。window.location和document.location引用同一个对象。
- URL片段
通过location.hash可以到url中的hash
-
查询字符串参数
function getQueryStringArgs() { //1.取得查询字符串并去掉开头问号 var qs=(location.search.length>0?location.search.substring(1):""); //保存数据的对象 var args={}; //3.取得每一项参数 var items=qs.length?qs.split("&"):[]; var item=null; var value=null; i=0; len=items.length; //逐个将每一项添加到args对象中 for(i=0;i<len;i++){ item=items[i].split("="); name=decodeURIComponent(item[0]); value=decodeURIComponent(item[1]); if(name.length){ args[name]=valuel } } return args; }
-
位置操作
-
打开新的URL并生成新记录,在本页面跳转
location.assign("https://ellenxx.com"); //或 window.location="https://ellenxx.com"; //或 location.href="http://ellenxx.com";
-
改变当前页面
可以将location的hash,search,hostname和port属性设置为新的值来改变当前页面。
//初始https://ellenxx.com/blog //将Url设置为https://ellenxx.com/blog/#s location.hash="#s"; //将Url设置为https://ellenxx.com/blog/?page=4 location.search="?page=4" ·······
-
禁止单击“后退“按钮回到前一个页面
replace()方法:接收一个参数为要导航到的URL,跳转之后不能通过退回回到之前的页面
setTimeout(function(){ location.replace("http://ellenxx.com"); },1000)
-
重新加载当前页面
reload()方法:不传任何参数,最有效的方式重新加载,也就是上次请求没改变过,页面就从缓存里加载;传入true,就要强制从服务器重新加载。
location.reload();//重新加载(有可能从缓存中加载) location.reload(true);//重新加载(从服务器加载)
-
下一节---->js——navigator,screen,history对象(BOM 3)
上一节---->js的window对象(BOM 1)