Javascript window.location.assign() 和 window.location.replace() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4505798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:41:03  来源:igfitidea点击:

Difference between window.location.assign() and window.location.replace()

javascriptwindow.location

提问by Bakudan

What is the difference between window.location.assign()and window.location.replace(), when both redirect to a new page?

当两者都重定向到新页面时,window.location.assign()和之间有什么区别window.location.replace()

回答by RedAnthrax

Using window.location.assign("url")will just cause a new document to load. Using window.location.replace("url")will replace the current document and replace the current History with that URL making it so you can't go back to the previous document loaded.

使用window.location.assign("url")只会导致加载新文档。使用window.location.replace("url")将替换当前文档并用该 URL 替换当前历史记录,从而使您无法返回上一个加载的文档。

Reference: http://www.exforsys.com/tutorials/javascript/javascript-location-object.html

参考:http: //www.exforsys.com/tutorials/javascript/javascript-location-object.html

回答by martona

The difference is how history is handled. "Replace" won't give you history, "assign" will.

不同之处在于如何处理历史。“替换”不会给你历史,“分配”会给你。

回答by Matt Ball

According to MDN:

根据 MDN:

The difference from the assign()method is that after using replace()the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

与该assign()方法不同的是,使用replace()当前页面后不会保存在会话历史记录中,这意味着用户将无法使用后退按钮导航到它。

回答by Mohideen bin Mohammed

  1. location.assign():

    To assign route path by passing path into it. Assign will give you a history even after path was assigned.

    Usage Method:Value should be passed into it.

    Eg:location.assign("http://google.com")

  1. location.assign():

    通过将路径传递给路径来分配路径路径。即使在分配了路径之后,Assign 也会为您提供历史记录。

    使用方法:传入值即可。

    例如:location.assign("http://google.com")

location.assign()

location.assign()

  1. location.replace():

    It helps to replace path if you don't want to keep history. It won't give you a history once you replace its path.

    Usage Method:Value should be passed into it.

    Eg:location.replace("http://google.com")

  1. location.replace():

    如果您不想保留历史记录,它有助于替换路径。一旦您替换其路径,它就不会为您提供历史记录。

    使用方法:传入值即可。

    例如:location.replace("http://google.com")

location.repalce()

location.repalce()