「JavaScript」document.locationでページのURLを参照する

関数
Document.location は読み取り専用のプロパティで、この文書の URL に関する情報を持った Location オブジェクトを返します。
構文
var locationオブジェクト名 = document.location
document.location = 'URL文字列’
document.location を使用して、ページのURLを参照/設定します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>document.locationサンプル</title>
<script>
function getUrlFunc(){
//当ページのURLを取得
var url = document.location;
alert(url);
}
function setUrlFunc(){
//URLにarkgameページを設定
document.location = 'https://www.arkgame.com';
}
</script>
</head>
<body>
<p><input type="button" value="URL取得" onclick="getUrlFunc();"></p>
<p><input type="button" value="URL設定" onclick="setUrlFunc();"></p>
</body>
</html>
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>document.locationサンプル</title> <script> function getUrlFunc(){ //当ページのURLを取得 var url = document.location; alert(url); } function setUrlFunc(){ //URLにarkgameページを設定 document.location = 'https://www.arkgame.com'; } </script> </head> <body> <p><input type="button" value="URL取得" onclick="getUrlFunc();"></p> <p><input type="button" value="URL設定" onclick="setUrlFunc();"></p> </body> </html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>document.locationサンプル</title>
<script>
function getUrlFunc(){
  //当ページのURLを取得
  var url = document.location;
  alert(url);
}
function setUrlFunc(){
  //URLにarkgameページを設定
  document.location = 'https://www.arkgame.com';
}
</script>
</head>
<body>
  <p><input type="button" value="URL取得" onclick="getUrlFunc();"></p>
  <p><input type="button" value="URL設定" onclick="setUrlFunc();"></p>
</body>
</html>

結果
「URL取得」ボタンを押すと、当ページのURLを表示します。

JavaScript

Posted by arkgame