LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】プルダウンメニューの作成

Last updated at Posted at 2020-11-11

プログラミング勉強日記

2020年11月11日
項目を選択すると別ページに移動するプルダウンメニューの作成をしました。

出力結果

pull-menu.gif

コード

htmlファイルは日本語用、英語用、中国語用の3つ用意します。
各htmlファイルのoptionタグにselected属性は使わずに作成しました。

index.html
 <section>
        <form action="" id="form">
            <select name="select">
                <option value="index.html">日本語</option>
                <option value="english.html">英語</option>
                <option value="zh.html">中国語</option>
            </select>
        </form>
        <h2>日本語のページ</h2>
    </section>
script.js
const lang = document.querySelector('html').lang;

if(lang === 'ja') {
    document.querySelector('option[value="index.html"]').selected = true;
} else if(lang === 'en') {
    document.querySelector('option[value="english.html"]').selected = true;
} else if(lang === 'zh') {
    document.querySelector('option[value="zh.html"]').selected = true;
}


document.getElementById('form').select.onchange= function () {
    location.href = document.getElementById('form').select.value;
}

コードの解説(自分用)

script.js

document.getElementById('form').select.onchange= function () {
    location.href = document.getElementById('form').select.value;
}
  • document.getElementById('form').selectはid属性がformの要素を取得し、form要素内でname属性がselectのvalue属性の値を取得します。

  • .onchangeは現在と違う<option>が選ばれたとき(例:日本語→英語、日本語→中国語)に発生するイベントです。

  • location.href = document.getElementById('form').select.value;はまずid属性がformの要素を取得します。次に、form要素内でname属性がselectのフォーム部品の値を取得します。その取得した値をlocation.hrefに代入します。

  • location.hrefでURLを書き換えています。ブラウザはURLが変更されると、即座に新しいページを表示しようとするので、すぐに次のページに移動できます。

script.js
const lang = document.querySelector('html').lang;
  • document.querySelector()は()内に書かれたCSSのセレクタを取得しています。今回の場合、htmlなので要素型セレクタを取得しています。

  • .langはhtmlタグのlang属性(例:ja、en、zh)を取得しています。

script.js
if(lang === 'ja') {
    document.querySelector('option[value="index.html"]').selected = true;
} 
  • document.querySelector('option[value="index.html"]')は、value属性の値がindex.htmlであるoption要素を取得します。

  • .selected = trueは取得したoption要素にselected属性を追加します。.selected = falseとするとselected属性を削除します。

  • その他のelse if文も役割は上記と同じです。

注意点

上記のif文がないと日本語から英語、日本語から中国語にはページの移動ができますが、英語から日本語、中国語から日本語のページには移動できません。

.onchangeイベントは現在と違うoption要素が選択されたときに発生します。

今回の場合、どのページを選択しても、最初にプルダウンメニューに選ばれているのは『日本語』です。

つまり、日本語のページから英語のページに移動して、また日本語のページに戻ろうとしても.onchangeイベントが発生せず、戻れないことになります。

下記にif文を書かなかったときの挙動を載せます。
not-pull.gif

参考資料

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0