【Labs】JavaScriptで前のページに戻るボタン
こんにちは(・∀・)
Webブラウザには必ず付いているもどるボタンですが、コンテンツ上にもボタンを付けたい場合があります。そういう時はJavaScriptのhistory.back()で簡単に実現することができます。
今までどういう訳かご紹介していなかったので(こういうの結構多いです(;'∀'))、今さらですがご紹介したいと思います。
Contents
1. history.back()
HTML
① <a href="javascript: history.back()">demo1a</a>
② <a href="javascript:void(0)" onclick="history.back(); return false">demo1b</a>
③ <button onclick="history.back()">demo1c</button>
④ <button id="demo1d">demo1d</button>
ボタン④のJavaScript
<script>
document.getElementById('demo1d').addEventListener('click',function(){
history.back();
},false);
</script>
2. history.go(-1)
HTML
① <a href="javascript: history.go(-1)">demo2a</a>
② <a href="javascript:void(0)" onclick="history.go(-1); return false">demo2b</a>
③ <button onclick="history.go(-1)">demo2c</button>
④ <button id="demo2d">demo2d</button>
ボタン④のJavaScript
<script>
document.getElementById('demo2d').addEventListener('click',function(){
history.go(-1);
},false);
</script>
3. history.go(1)
HTML
① <a href="javascript: history.go(1)">demo3a</a>
② <a href="javascript:void(0)" onclick="history.go(1); return false">demo3b</a>
③ <button onclick="history.go(1)">demo3c</button>
④ <button id="demo3d">demo3d</button>
ボタン④のJavaScript
<script>
document.getElementById('demo3d').addEventListener('click',function(){
history.go(1);
},false);
</script>
4. history.forward(1)
HTML
① <a href="javascript: history.forward(1)">demo4a</a>
② <a href="javascript:void(0)" onclick="history.forward(1); return false">demo4b</a>
③ <button onclick="history.forward(1)">demo4c</button>
④ <button id="demo4d">demo4d</button>
ボタン④のJavaScript
<script>
document.getElementById('demo4d').addEventListener('click',function(){
history.forward(1);
},false);
</script>
Result
history.back()で前のページにもどります。history.back(-2)で前の前のページにもどります。