2016-04-07 5 views
1

モルの画像をクリック可能にしようとしましたが、一度クリックするとスコアが高くなりますが、.on()は画像のクラス名では機能しません。しかし、セレクタ「#gamespace」を使用すると動作しますが、ゲーム空間内のどこかをクリックすると、単にモルをクリックするのではなく、プレイヤーのポイントが得られます。Jquery .on()が呼び出しセレクターではない

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

答えて

3

あなたはそれはあなたが「のクリックイベントにバインドしようとしているように見える代わりに

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

それはそれでした!恥ずかしいほどシンプルだけど、それについては考えていない - 明らかに私はこれで非常に新しいです。ありがとうございました!!! – ecooper10

1

をイベントの委任を使用し、それは#gamespaceに追加される前に、.moleclick event handlerを追加し、ページ上に存在しています。モルが存在する前に。ダイレクトバインディングは、DOMにすでに存在する要素に対してのみ機能します。デリゲートバインディングを行うことでこれを修正できます。

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

これは、モル要素からのバブリングされたイベントをリッスンします。バブリングされたイベントで動作するので、作成時は問題ありません。

+0

これは機能しています。ご協力ありがとうございました! – ecooper10

関連する問題