2016-10-30 42 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

是的!如果可能的話,我會讓你百倍。這是我尋找的解決方案,非常感謝! – KikePeris