2014年10月30日木曜日

イベントリスナでタグにイベントハンドラを登録する

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>event handler</title>
<script>
function exe(){
    window.alert("ボタンを押しました!");
}
</script>
</head>
<body>
    <input type="button" value="押す" onclick="exe();">
</body>
</html>

上記のコードのようなボタンのタグを追加して、タグ内にonclick="exe();"といったJavaScriptの関数とつなぎこむonclickのようなものをイベントハンドラと呼びます。
(他にはonkeyupやonkeydownとか)

今回のサンプルコードでは、ボタンのタグに直接記述していますが、JavaScriptのコードでボタンタグにイベントハンドラを追加することが出来ます。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>event handler</title>
<script>
window.onload = function(){
    var button = document.querySelector("#button");
    button.addEventListener("click", exe);
};

function exe(){
    window.alert("ボタンを押しました!");
}
</script>
</head>
<body>
    <input type="button" value="押す" id="button">
</body>
</html>

ボタンのタグをdocument.querySelectorで取得できるようにidを付与して、window.onload内でボタンのオブジェクトを取得して、イベントリスナ(addEventListener)でイベントハンドラを登録します。addEventListenerの第一引数には、登録したいイベントハンドラ(今回はclick)を入れ、第二引数には登録したイベントハンドラを実行した時に実行したい関数を指定します。これで、<input type="button" onclick="exe();">と同等の実装になりました。

特定のタグではなく、表示しているブラウザ全体にイベントハンドラを追加したい時、

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sample</title>
<script>
window.onload = function(){
    document.addEventListener("click", exe);
};

function exe(){
    alert("クリックしました!");
}
</script>
</head>
<body>
</body>
</html>

documentオブジェクトでaddEventListenerを実行して、イベントハンドラを登録すれば実行できるようになります。

0 件のコメント:

コメントを投稿