[关闭]
@gongzhen 2017-12-29T06:54:35.000000Z 字数 859 阅读 1547

页面跳转

js


window.location 和 document.location

那么 window.locationdocument.location 有什么区别呢?我认为是没有区别的,我已经在多个浏览器中不同页面(包括 iframeframe)中测试了。有人说一个可写,一个只读,这一点也在我的测试中被否定了。同样在 MSDN 中说 location 应用于 windowdocument,但并未提出二者有区别。所以我认为二者是没有区别的。如果说实在有区别,可能也是 windowdocument 的区别,从这个方面看,可能用 document 更合适一些:

location.href, location.replace, location.assign

三者都用来跳到一个新的url,区别是 hrefassign 做跳转时会将新地址放到浏览器历史栈中,意味着转到新页面后“后退按钮”仍可以回到该页面(经测试,hrefassign 使用没区别)。而 replace 会从浏览器历史栈中删除本页面,也就是说跳转到新页面后“后退按钮”不能回到该页面。

用个例子来说明:
假设有A.htm B.htm C.htm三个页面
A.htm里有这样一句:document.location.href="b.htm";
B.htm里有这样一句:document.location.href="c.htm";
注意两个都是可回退的切换。

1: 当从A切换到B再切换到C时,实际内存中保留了三个页面:A、B、C
2: 回退到B时,C页面被清出内存!
3: 再次回退,到A页面时,B页面也被清出内存!
4: 再次向前(不是用切换而是用向前)转到B页面时,内存中保留了两个页面:A、B

如果B.html里是用的replace跳转:document.location.replace('c.html'), 则在C页面点后退时会直接退到A

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注