Index

HOME > プログラムTOP > JavaScript



ページの移動

 JavaScript の実用的なTips集です。ここでは、history オブジェクトや location オブジェクトなどを利用してページを移動させる方法を扱います。
[INDEX] 履歴を利用した移動... historyオブジェクトを使ってページを移動
指定した場所に移動... locationオブジェクトで指定したページに移動
フレーム上での移動... 特定のフレームのページを移動

sasaraan programming

Exposition

■履歴を利用した移動

 history オブジェクトとそのメソッドを使って、ページを移動させることができます。ただし、履歴がなければ何も起こりません。
history.back()  : 一ページ分戻る
history.forward() : 一ページ分進む
history.go(n) : n ページ分移動する(+値で進む・−値で戻る)
// 一つ戻る
history.back();

// 一つ進む
history.forward();

// 三つ進む
history.go(3);

// 二つ戻る
history.go(-2); 

■指定した場所に移動

 指定した場所への移動には、location オブジェクトを使用します。document オブジェクトの location プロパティに値を設定することでも同様に移動させることができます。
location.reload()  : 現在と同じページを再度読み込む
location.replace(uri) : 指定したページ (uri) に置き換える(履歴には残らない)
location.href = uri : 指定したページ (uri) に移動する(履歴に残る)
document.location = uri : 指定したページ (uri) に移動する(履歴に残る)
// 再読み込み
location.reload();

// ページの置き換え(現在のページは履歴に残らない)
location.replace("jspage.html");

// ページの移動
location.href = "jspage.html";

// ページの移動
document.location = "jspage.html"; 

■フレーム上での移動

 フレームに分割されている場合は、表示するフレームのオブジェクトを取得してからページを読み込ませます。方法は前節と同じ location オブジェクトや document オブジェクトを利用します。
obj.location.href = uri : obj (フレーム)にページ (uri) を読み込む
(window.)parent : 現在の親フレームを指します
(window.)top : ルートページを指します
(window.)self : 自分自身のフレームを指します
(window.)opener : 現在のウィンドウを開いたウィンドウを指します
<!-- "FramePage" HTML Source -->

<frameset rows="100, *">
     <frame src="navi.html" name="cap">
     <frameset cols="40%, *">
          <frame src="menu.html" name="left">
          <frame src="view.html" name="right">
     </frameset>
</frameset>

<!-- "PAGE 1" HTML Source -->

<form>
<input type="button" value="Change LeftPage" 
          style="padding:0.5ex 0;" onclick="ChangeFrame(1)"/>
<input type="button" value="Change RightPage" 
          style="padding:0.5ex 0;" onclick="ChangeFrame(2)"/>
<input type="button" value="Change Parent" 
          style="padding:0.5ex;" onclick="ChangeFrame(0)"/>
<input type="button" value="CLOSE" 
          style="padding:0.5ex 1ex;" onclick="parent.close();"/>
</form>

<!-- "PAGE1" JavaScript Source -->

var currL = 2;  // 左側のページの現在のページ番号
var currR = 3;  // 右側のページの現在のページ番号

function ChangeFrame(index) 
{
     if (index == 0) {                 /* 親ページ */
          parent.location.href = "frame_pg6.html";
     } else if (index == 1) {        /* 左側のページ */
          currL = currL==2? 4: 2;
          parent.left.location.href = currL==2? "frame_pg2.html": "frame_pg4.html";
     } else if (index == 2) {         /* 右側のページ */
          currR = currR==3? 5: 3;
          parent.right.location.href = currR==3? "frame_pg3.html": "frame_pg5.html";
     }
} 

www.sasaraan.net

(c) morijoh