JavaScript 页面常见操作:跳转、刷新、关闭

1. window.location

href、assign()、replace() 跳转页面

href 属性 和 assign()方法 用于跳转页面功能一样,只是写法不同,保留缓存历史,可回退

replace()方法 跳转页面,删除历史缓存,无法回退

2.刷新页面

重新加载当前页面

3.获取和设置当前页面 url 的相关信息

console.log(window.location.href);//完整url:协议名.域名:端口号/路径/?参数#hashconsole.log(window.location.protocol);// 协议号console.log(window.location.host);//域名和端口号console.log(window.location.hostname);//域名console.log(window.location.port);// 域名后的端口号console.log(window.location.pathname);// 端口号后的路径console.log(window.location.search);// 参数 格式:?id=1console.log(window.location.hash);// # hash参数

2. window.history


需要有历史缓存,才可操作

window.history.forward();// 浏览器前进window.history.back();// 浏览器后退window.history.go(-1);// 浏览器后退window.history.go(0);// 刷新页面window.history.go(1);// 浏览器前进window.history.go(num);// 跳转到指定的历史记录页// 功能:切换到指定url,不重新加载页面// state:状态对象可以是任何可以序列化的对象,JSON对象,(获取方式:window.history.state)// name:标题名称,浏览器兼容性极差,建议传 ''// url:新历史记录条目的URL,相对或者绝对路径,不传代表当前页面url(可直接传:?参数=参数值),注意:url必须同域,否则无效history.pushState(state,name,url);history.replaceState(state,name,url);console.log(window.history.length);// 获取缓存历史的条数 最少时 1// 使用 pushState 和 replaceState 时,调用此事件window.addEventListener("popstate",function(e){consturl=window.location.href;console.log("url);console.log(e.state);// 获取页面参数 state 对象});

 3.window 打开和关闭新窗口


// 保留当前页面,打开子窗口

// url:打开子窗口的路径// name:打开子窗口的名称// 宽高:设置打开子窗口的宽高,默认100%// newWindow:返回子窗口的window,可对子窗口进行操作constnewWindow=window.open(url,name,宽高);window.open("http://www.baidu.com",'新标题','width=200,height=100');// 关闭当前页面window.close();

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容