首先,這兩個方式都可以實現頁面跳轉:
location.href = 'https://www.baidu.com'
location.replace('https://www.baidu.com')
那麼,它們的區別是什麼呢?
location.href | location.replace() |
---|---|
跳轉後,URL 會被寫入 history 對象中 | 替換當前 URL,被替換掉的 URL 不會被寫入 history 對象中 |
也就是說,如果使用 location.href 的方式實現的跳轉,點擊返回,會返回到上一個頁面,
而如果使用的是 location.replace() 的方式,點擊返回,無法返回到之前的頁面。因爲 history 對象中沒有之前的頁面的記錄。