Webブラウザのイベント処理1
【開発環境】
OS;Window10
Webブラウザ:Google Chrome
テキストエディタ:Brackets
---イベント処理の基礎知識---
【イベントと、イベントハンドラ】
イベントとは→ユーザがボタンをクリックしたり、テキストボックスに文字を入れて【Enter】キーをおした時に、ブラウザから送出されるメッセージのようなものです。
イベントハンドラ→発生したイベントを捕まえて、それに対して何らかの処理を行うプログラムの事。

・イベント処理の3つの方法
1)HTMLタグの属性で設定する
2)エレメントオブジェクトのプロパティとして設定する
3)イベントリスナーで設定する
◆HTMLタグの属性で処理を設定する
ア)ボタンのクリックを捕まえる
・ボタンの設定
<input type="button" value="クリックして" id="myBtn"
・イベントハンドラの設定
onclick="alert('クリックされました'); console.log('クリックされました')">

「クリック」ボタンをクリックする→アラートダイアログ表示

イ)イベントハンドラを関数に!
例文

同じ結果に成る
ウ)イベントが発生したエレメントを調べる→「this」を使う。
・例文
省略
<body>
<input type="button" value="クリックして" id="myBtn" onclick="clickHandler(this)">
<script>
function clickHandler(el) {
alert(el.id + "がクリックされました");
}
</script>
</body>
実行
・「クリック」ボタンをを押すと、アラートダイアログが表示される

◆オブジェクトのプロパティとしてイベントハンドラを設定する
ア)onclickプロパティにコールバック関数を登録
例えば、「myBtn」ボタンを設け、それがクリックされた時に呼び出されるイベントハンドラの関数を登録するには、下記のようにする。
書式
myBtn.onclick = 関数;
例文

var myBtn = document.getElementById("myBtn");→ドキュメント要素を取得している
myBtn.onclick = clickHandler;→関数を登録している
実行する

◆コールバック関数を無名関数にする
無名関数→一度しか呼ばない関数
例文

実行

◆イベントハンドラを削除する
プロパティに代入した後に、イベントハンドラを削除することができる。
element.onclick = null;
◆イベントハンドラとして使用するプロパティ

◆onloadイベントハンドラ
HTMLドキュメントの読み込みが完了したときのイベントを呼び込む、イベントハンドラ
例文

実行

・onloadはheadエレメントにプログラムを記述する時に必要
headエレメントに書くと、エラーになり、動作しない。
なぜなら、すべてのエレメントが読み込まれてないからである。

改造後→windowのonloadイベンドハンドラに処理を記述すれば良い。そうすることで、HTMLドキメントのロード完了待ってから処理を実行できる。

表示

※コメント投稿者のブログIDはブログ作成者のみに通知されます