2016-10-30 11 views
0

私は自分のリンゴイメージをクリックすると非常に簡単なことをしようとしています。私のキャラクタイメージ(Anthony)の横に表示されたテキストと私のappleNumber div内の数字を取得する必要があります。私はaddEventListenerを使用しましたが、何かが間違っているようです(私はChromeにいる)。コード:私のaddEventListenerが動作していません

<script> 
    var appleButton = document.getElementById("apple"); 
    appleButton.addEventListener("click", showAnthonyText); 
    appleButton.addEventListener("click", showNumber); 

    function showAnthonyText() { 
     document.getElementById("anthonyDelishBubble").style.display='block'; 
    } 
    function showNumber() { 
     document.getElementById("appleNumber").innerHTML = "1"; 
    } 
    </script> 

<body> 

     <div id="anthonyGameTitle">Feed Amicable Anthony Some Apples</div> 
     <div id="anthonyGameMainContainer"> 
      <div id="anthonyAppleGame"><img src="AmicableAnthony.png" alt="AmicableAnthony" height="300" width="300"></div> 
      <div id="apple"><img src="apple.png" alt="apple" height="80" width="80"></div> 
      <div id="anthonyDelishBubble"><img src="delish.png" alt="delish" height="80" width="80"></div> 
      <div id="appleNumber"></div> 


     </div> 
    </body> 
+0

はエラーについて、コンソールを見てください。 –

+0

まだ存在しない要素への参照を取得して使用しようとしていますが、どうすればいいですか... ... – KikePeris

答えて

0

あなたのHTMLは、まだ読み込まれていないときに実行されます。あなたの体は、例えばロードされたときに起動機能でコードを実行します。

<script> 
function init() { 
    var appleButton = document.getElementById("apple"); 
    appleButton.addEventListener("click", showAnthonyText); 
    appleButton.addEventListener("click", showNumber); 
} 

function showAnthonyText() { 
    document.getElementById("anthonyDelishBubble").style.display = 'block'; 
} 

function showNumber() { 
    document.getElementById("appleNumber").innerHTML = "1"; 
} 
</script> 

<body onload="init()"> 
..... 
</body> 

またはあなたのhtmlの後に初期化を追加します。

<body> 

    <!-- your html body here --> 

    <script> 
    var appleButton = document.getElementById("apple"); 
    appleButton.addEventListener("click", showAnthonyText); 
    appleButton.addEventListener("click", showNumber); 

    function showAnthonyText() { 
     document.getElementById("anthonyDelishBubble").style.display = 'block'; 
    } 

    function showNumber() { 
     document.getElementById("appleNumber").innerHTML = "1"; 
    } 
    </script> 
</body> 
+0

あなたの助けを借りて非常に感謝していますが、w3schoolsの例のように正確に行いました。体に "onload"を使用しないでください、より簡単な方法はありますか? – KikePeris

+0

はい!もし私ができるなら、私はあなたに100倍アップアップします。それは私が探していた解決策でした、ありがとうございました! – KikePeris

関連する問題