window.location.href vs window.location.replace vs window.lo
window.location.href vs window.location.replace vs window.location.assign in JavaScript
-
window.location.href="http://example.com";
-
window.location.replace("http://example.com");
-
window.location.assign("http://example.com");
我在很多论坛上看到window.location.assign()
只是取代了当前的会话历史记录,因此浏览器的后退按钮将不起作用。然而,我无法复制这一点。
function fnSetVariable() {
//window.location.href = "http://example.com";
window.location.replace("http://example.com");
//window.location.assign("http://example.com");
}
<a onmouseover="fnSetVariable();"
href="PageCachingByParam.aspx?id=12" >
CLICK
</a>
它们的作用相同:
window.location.assign(url);
window.location = url;
window.location.href = url;
它们只是导航到新的URL。另一方面,replace
方法导航到URL,而不向历史记录添加新记录。
所以,你在那些论坛上读到的是不正确的。assign
方法确实向历史记录中添加了一条新记录。
参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/location
关于不能使用后退按钮的部分是一个常见的误解。window.location.replace(URL)从页面历史列表中抛出top ONE条目,用新的条目覆盖它,这样用户就不能轻易地回到那个特定的网页。该函数不会清除整个页面历史列表,也不会使后退按钮完全失效。
(据我所知,没有任何函数或参数组合可以改变或覆盖您不绝对拥有的历史列表条目-浏览器通常通过简单地甚至不定义任何可能影响页面历史列表中顶部以外的任何条目的操作来实现此安全限制。)我不寒而栗地想到,如果这样的功能存在,恶意软件可能会做出什么样的卑鄙的事情。
如果你真的想让后退按钮没有功能(可能不是"用户友好":如果这真的是你想做的,再考虑一下),"打开"一个全新的窗口。(你可以"打开"一个甚至没有有一个"返回"按钮的弹出窗口…但是现在弹出窗口并不是很流行:-)如果你想让你的页面无论用户做什么都显示出来(再一次,"用户友好"是值得怀疑的),设置一个窗口。Onunload处理程序只是重新加载你的页面,每次都从最开始清除。
location, location。href和location.assign()可以转到URL,将记录添加到历史记录中,以便我们可以返回到上一页:
location = "http://example.com";
location.href = "http://example.com";
location.assign("http://example.com");
location.replace()可以转到URL而不将记录添加到历史记录中,因此我们不能返回到上一页:
location.replace("http://example.com");
- Javascript events: window.event vs argument reference (funct
- Javascripts commands: window.alert vs console.log
- window.outerWidth VS $(window).outerWidth()
- 移动野生动物园:frame.src vs window.location
- window.location.pathname Chrome vs Mozilla
- window.find() in Firefox vs Chrome
- window.onload vs jQuery(document).ready
- setTimeout(0) vs window.postMessage vs MessagePort.postMessa
- JSON 解析错误:window.onload vs XMLHttpRequest
- this.globalvar vs window.globalvar
- 美元(窗口).load vs. window.addEventListener
- IE8+, window.open(url/#/frag,'_parent') vs. parent.l
- 使用 document.ready vs window.load 来加载延迟的内容
- window.location.href vs window.location.replace vs window.lo
- window.localStorage vs chrome.storage.local
- Window vs Var来声明变量
- FileReader vs. window.URL.createObjectURL
- getElementById vs $('#element') vs window.document.l
- window.innerWidth vs document.documentElement.clientWidth
- window vs this作为IIFE中的参数