我的addEventListener不起作用

时间:2016-10-30 00:02:19

标签: javascript html

我尝试做一些非常简单的事情,当我点击我的苹果图像时,我应该在我的角色图像(Anthony)旁边显示一个文本,并在我的appleNumber div中显示一个数字。我使用了addEventListener,但似乎有些不对劲(我在Chrome上)。代码:

<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>

1 个答案:

答案 0 :(得分: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>