質問失礼いたします。javascriptで数当てゲームを作成中にエラーが出てきましたが解決できませんでした。1回目のボタンを押すと正常に動きますが、2回目ではthis.numberの値はundefinedになり、
3回目のボタンからエラーがでます。
この原因と対処法をご教授いただけると幸いです。
エラーコードをググってみたのですが、解決には至りませんでした。
html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Document</title> </head> <body> <div id="container"> <h1>1~100の間の数字を当ててください!</h1> <input type="number" id="input"> <button id="btn">解答する</button> <p class="result"></p> </div> <script src="main.js"></script> </body> </html>
scss
#container{ width: 50%; margin: 0 auto; } h1{ font-size: 24px; margin-bottom: 50px; } #btn{ width: 100px; text-align: center; padding: 5px 10px; display: block; } .result{ margin-top: 50px; }
js
document.addEventListener('DOMContentLoaded', function(){ const wN = new WinNumber(); }); class WinNumber{ constructor(){ this.randomNumber = Math.floor(Math.random() * 101); this.btn = document.querySelector('#btn'); this.number = document.querySelector('#input'); this.result = document.querySelector('.result'); this.accu = 0; this.btn.addEventListener('click',this._checkNumber.bind(this)); } _checkNumber(){ this.number = this.number.value; this.accu += 1; if(this.number == false){ this.number = 0; } if(this.number < this.randomNumber){ this.result.innerHTML = `${this.accu}回目 ${this.number}は小さいです`; }else{ this.result.innerHTML = `${this.accu}回目 ${this.number}は大きいです`; } } }
まだ回答がついていません
会員登録して回答してみよう