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