JavaScript での window.location.href と window.location.replace と window.location.assign の比較 質問する

JavaScript での window.location.href と window.location.replace と window.location.assign の比較 質問する

違いは何ですか

  1. window.location.href="http://example.com";
  2. window.location.replace("http://example.com");
  3. 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>

ベストアンサー1

これらは同じことを行います:

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/場所

おすすめ記事