我试图使痣的图像可点击,一旦单击将增加得分,但.on()将不适用于图像的类名。但是,如果我使用选择器“ #gamespace”,它将起作用,但是单击游戏空间中的任何位置将获得玩家点数,而不仅仅是单击痣。

<!DOCTYPE html>
<html>
  <head>

    <title>Whack-A-Mole (CSCI2447)</title>

    <!-- CSS styles: This is for me to worry about; not you. -->
    <link href="css/game.css" rel="stylesheet" />
    <script src="js/jquery-2.2.1.min.js"></script>
    <script type="text/javascript">
    var score = 0
    var time = 30
    var t;
    var moleRepeat;
    $(document).ready(function(){
    $('#start_button').click(function (){
    start();
    });
    $('.mole').on('click' , function () {
    counter();
    });
    });

    function getYRandomNumber(){
        return Math.floor((Math.random()*300)+0);
      };

    function getXRandomNumber(){
        return Math.floor((Math.random()*600)+0);
      };

     function counter() {
     score++;
     $("#score").html(score + ' pts');
     };

     function start() {
     $('#timer').show();
     addMole();
     decrement();
     $('h1').css("color","purple");
     $('#gamespace').css("background-color", "green");
     };

     function decrement() {
     time--;
     $('#timer').html(time + ' seconds left');
     t = setTimeout('decrement()', 1000);
     };

     function addMole() {
     $('#gamespace').append('<img class="mole" src="img/mole.png" onClick="counter()"/>');
     moleRepeat = setTimeout('addMole()', 2000);
     };
    </script>
  </head>
  <body>

    <div id="content">

        <h1>Whack-A-Mole</h1>

        <p>After clicking "start", you will have 30 seconds to click
        as many moles as you can. The moles appear randomly so be ready! </p>

        <div id="controls">
            <span id="score">0 pts</span>
            <button type="button" id="start_button">Start!</button>
        </div>

        <div id="timer">30 seconds left</div>

        <div id="gamespace">



        </div>

    </div>
  </body>
</html>

最佳答案

您要在click event handler上添加.mole,然后将其附加到#gamespace并存在于页面上,请改用事件委托

$('#gamespace').on('click','.mole' ,function () {
    counter();
 });

07-28 11:08