window.location.hrefの概要
href(エイチレフ)というのは略称です。実際は hypertext reference のことでハイパーテキスト参照という意味になります。
Windowオブジェクトのlocation.hrefプロパティを使うとa要素を使用しないでリンクを作成することが出来ます。 Windowオブジェクトはwindow変数から参照します。
実機サンプルとサンプルコード
同じページのid属性をターゲットにリンクする場合
<body>
<button id="idGoFooter">このページのフッター(idFooter)に移動</button>
<script>
document.open();
document.getElementById("idGoFooter").addEventListener("click",function(){
window.location.href = "#idFooter";
});
document.close();
</script>
<footer id="idFooter">
ここがidFooterの場所です
</footer>
</body>
通常のページ移動をする場合
<body>
<button id="idGoIndex">このサイトのトップページ(index.html)に移動</button>
<script>
document.open();
document.getElementById("idGoIndex").addEventListener("click",function(){
window.location.href = "../index.html";
},false);
document.close();
</script>
</body>
このページをもう一つ別ウィンドウで開く場合
<body>
<button id="idNewThisPage">このページをもう一つ別ウィンドウで開く</button>
<script>
document.open();
document.getElementById("idNewThisPage").addEventListener("click",function(){
window.open().location.href = window.location;
},false);
document.close();
</script>
</body>
サンプルコードの要点
- hrefプロパティを利用すると基本的にa要素と同じ動作ができる。
- window変数.open()メソッドから.location.hrefを指定すると新規ウィンドウでページが開く
- window変数.locationプロパティでこのページのURLが取得できる