this?
by yshrkn
HTML
<ouput id="total"></ouput><br>
<input type="button" value="1" class="add-button">
<input type="button" value="5" class="add-button">
<input type="button" value="10" class="add-button">
CSS
#total {
display: inline-block;
padding: 5px;
border: 2px solid black;
min-width: 50px;
background-color: #fff;
text-align: right;
margin-bottom: 10px;
}
input[type="button"] {
padding: 10px;
}
img {
cursor: pointer;
}
JavaScript
/**
* クリックしたボタンの値を#totalに加算表示してください。
*/
//----------------------------------------------
// Example Class
//----------------------------------------------
class ExampleClass {
/**
* クラスコンストラクタ(インスタンス生成時に実行される関数です)
*/
constructor() {
// カウンターに初期値を設定
this.counter = document.getElementById('total');
this.result = 0;
this.counter.textContent = this.result;
// ボタンにクリックイベントリスナを登録
this.buttons = document.querySelectorAll('.add-button');
for (let i = 0, len = this.buttons.length; i < len; i++) {
this.buttons[i].addEventListener('click', this.onButtonClick.bind(this))
}
}
/**
* インスタンスメソッド
* (ここでは、ボタンのイベントリスナとして使用します。)
*/
onButtonClick(event) {
this.result += parseInt(event.currentTarget.value, 10);
this.counter.textContent = this.result;
}
}
// クラスをインスタンス化
new ExampleClass();