【JavaScript】一つのイベント処理を複数の要素に紐づけるイベントリスナー
各ボタンに対し、同じイベントを付与。
コード内容
■HTML
1 2 3 4 5 |
<div id="buttons"> <input type="button" value="ボタン1"> <input type="button" value="ボタン2"> <input type="button" value="ボタン3"> </div> |
■JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 |
//ボタン要素を取得してonclick属性を付与する document.addEventListener('DOMContentLoaded', function() { var s = document.getElementById('buttons'); var child = s.firstElementChild; while (child) { child.addEventListener('click', function() { window.alert('ボタンが押されました。'); }, false); child = child.nextElementSibling; } }, false); |
タグ :
DOM, JavaScript