URLを取得したり、書き換えたりするサンプルです。
サンプルコード(URLを取得)
JavaScript
// 現在のURL全体を取得
document.getElementById('href').innerHTML = location.href; // https://cly7796.net/blog/sample/location-url/index.html?param=abc#hash
// 現在のURLのプロトコル部分(「http:」や「https:」)を取得
document.getElementById('protocol').innerHTML = location.protocol; // http:
// 現在のURLのホスト情報を取得
document.getElementById('host').innerHTML = location.host; // cly7796.net
// 現在のURLのパスを取得
document.getElementById('pathname').innerHTML = location.pathname; // /wp/sample/location-url/index.html
// 現在のURLのパラメータを取得
document.getElementById('search').innerHTML = location.search; // ?param=abc
// 現在のURLのハッシュを取得
document.getElementById('hash').innerHTML = location.hash; // #hash
HTML
<dl> <dt>URL全体を取得:</dt> <dd id="href"></dd> </dl> <dl> <dt>URLのプロトコル部分:</dt> <dd id="protocol"></dd> </dl> <dl> <dt>URLのホスト情報:</dt> <dd id="host"></dd> </dl> <dl> <dt>URLのパス:</dt> <dd id="pathname"></dd> </dl> <dl> <dt>URLのパラメータ:</dt> <dd id="search"></dd> </dl> <dl> <dt>URLのハッシュ:</dt> <dd id="hash"></dd> </dl>
サンプルコード(URLを変更)
JavaScript
$(function() {
// URLの変更(ページ遷移)
$(document).on('click', '#sample', function() {
location.href = 'https://cly7796.net/blog/';
});
// パラメータ追加
$(document).on('click', '#sample2', function() {
location.search = '?param=abc';
});
// ハッシュ追加
$(document).on('click', '#sample3', function() {
location.hash = '#hash';
});
});
HTML
<button id="sample">URL変更</button> <button id="sample2">パラメータ追加</button> <button id="sample3">ハッシュ追加</button>
コメントが承認されるまで時間がかかります。