クリックイベントにイベントハンドラをバインド

JavaScriptで、id指定した要素のクリックイベントに、イベントハンドラをバインドするサンプル。

この方法を使うと、クリックによる関数呼び出しを、JavaScript側で一元管理できる。

HTML要素のonclick属性から直接呼び出すより、HTMLコードもシンプルになる。

構文

window.onload = function () {
    document.getElementById( "ID" ).onclick = 関数名;
}

バインド例

window.onload = function () {
    document.getElementById( "sample" ).onclick = sampleFunction;
}

idが「sample」である要素をクリックすると、関数「sampleFunction」を呼び出す。

実装例(サンプル)

1

実装例の動作について

「1を足す」ボタンをクリックすると、赤い背景のボックス内の数値に1を足す。

「2を足す」ボタンをクリックすると、赤い背景のボックス内の数値に2を足す。

ソースコード

JavaScript

<script type="text/javascript">
window.onload = initialize;
function initialize() {
    document.getElementById( "funcAdd1" ).onclick = funcAdd1;
    document.getElementById( "funcAdd2" ).onclick = funcAdd2;
}
function funcAdd1() {
    document.getElementById( "sample" ).innerHTML =
        parseInt( document.getElementById( "sample" ).firstChild.nodeValue ) + 1;
}
function funcAdd2() {
    document.getElementById( "sample" ).innerHTML =
        parseInt( document.getElementById( "sample" ).firstChild.nodeValue ) + 2;
}
</script>

HTML

<div id="sample">1</div>
<div id="sampleButton">
    <button id="funcAdd1">1を足す</button>
    <button id="funcAdd2">2を足す</button>
</div>

CSS

<style type="text/css">
#sample {
    width: 300px;
    padding: 30px;
    font-size: 30px;
    background-color: red;
    color: white;
    text-align: center;
    border-radius: 10px;
}
#sampleButton {
    width: 360px;
    margin-top: 5px;
    text-align: center;
}
#sampleButton button {
    font-size: 16px;
}
</style>

スポンサード リンク

カテゴリー: JavaScript, イベント, 逆引き パーマリンク