ボタンのvalue属性を使って、イベントの内容を動的に変化させるサンプル。
ソースコード
■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 13 14 |
document.addEventListener('DOMContentLoaded', function() { var frag = document.createDocumentFragment(); var buttons = document.getElementById('buttons'); var child = buttons.firstElementChild; while(child) { child.addEventListener('click', function(e) { var data = e.target.getAttribute('value'); window.alert(`${data}が押されました。`); }) child = child.nextElementSibling; } }, false) |
このように書いても動く。
1 |
var data = this.getAttribute('value'); |