2016-09-03 7 views
-2

私はTic Tac Toeゲームを作成しています。なぜ私の `addEventListener`は動作していませんか?

ページが読み込まれると、htmlは「開始ページ」にリセットされます。だから私は後でそれを簡単に追加します。元のhtmlの本体は変数に格納されています。

ユーザーが「開始」ボタンをクリックすると、元のHTMLが再び読み込まれます。

なぜこれが現在機能していないのですか?

(function() { 

    'useStrict'; 


// Grab original HTML and hold it as a variable 
    var originalHTML = document.body.innerHTML; 


// When the page loads, the startup screen should appear. 
    window.onload = function() { 
     document.body.innerHTML = '<div class="screen screen-start" id="start"><header><h1>Tic Tac Toe</h1><a href="#" class="button">Start game</a></header></div>'; 
    }; 



// Add programming, so that when the player clicks the start button the start screen disappears, the board appears, and the game begins. 
    function loadBoard() { 
     document.body.innerHTML = originalHTML; 
    }; 

    document.querySelector('button').addEventListener("click", loadBoard); 


})(); 

エラーは次のとおりです。nullのプロパティ 'addEventListener'を読み取ることができませんか?

+2

'querySelector'関数は' button'要素を見つけることができないようです。おそらく、 '.button'と打つことを意図していたでしょうか? 'button'はクラスであり、' querySelector'を使うときにはそのように識別されるべきであるので、これは意味をなさないでしょう。 – Xetnus

+0

奇妙なことに、あなたが言ったことは完全ではありますが、まだ動作していないことです: – gloopit

+2

HTMLの 'onload'を設定しましたが、それまで待ってイベントリスナをアタッチしようとしません。また、 'use strict'ではなく' use strict'です。 –

答えて

1
window.onload = function() { 
     document.body.innerHTML = '<div class="screen screen-start" id="start"><header><h1>Tic Tac Toe</h1><a href="#" class="button">Start game</a></header></div>'; 
document.querySelector('a').addEventListener("click", loadBoard); 
    }; 
関連する問題