2017-02-03 53 views
1

最近我開始學習HTML/CSS和jQuery,所以我試圖做一個小型的網頁遊戲。這裏是HTML的代碼:事件監聽器在追加後不工作

function playGame() { 
 
     var theLine = "<div id = \"line\">"; 
 

 
     for (var i = 0; i < 9; i++) { 
 
      theLine = theLine + "<button class=\"ticButton\"> chose </button>"; 
 
     } 
 

 
     theLine = theLine + "</div>"; 
 
     var instr = "<p id = \"ins\"> choose wisely </p>"; 
 

 
     $("body").append(instr); 
 
     $("body").append(theLine); 
 
    } 
 

 
    $(document).ready(function() { 
 
     $("#game").click(function() { 
 
      alert("be aware"); 
 
      $("#game").hide(); 
 
      playGame(); 
 
     }); 
 

 
     $(".ticButton").click(function() { 
 
      alert("you won"); 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
    <html> 
 
    <head> 
 
\t <title> Play </title> 
 
\t <script src="jquery-3.1.1.js"></script> 
 
\t <script src="behavior.js" type="text/Javascript"></script> 
 
\t <link href="style.css" rel = "stylesheet" type="text/CSS" /> 
 
    </head> 
 
    <body> 
 
\t <h1> Welcome </h1> 
 
\t <button id="game"> play </button> 
 
\t 
 
    </body> 
 
    </html>

所以我的目的,點擊播放(ID =遊戲)按鈕後,應該出現了9點新的按鈕,然後點擊其中的任何警報後應該提出說:你贏了。但是會發生什麼:在9個新按鈕出現後,點擊它們時就沒有任何反應。 有什麼建議嗎? 我想提一下,有一個關於事件監聽器的問題,它在動態創建之後不起作用,但是這個問題及其答案對我沒有幫助。

+1

聲明你的事件沒有你的意思'$( 「#遊戲」)的''而不是$( 「遊戲」)'? – mic4ael

+0

@ mic4ael「_But發生了什麼:在9個新按鈕出現後......_」所以這看起來像是一個簡單的錯字,否則'playGame()'不會執行 – Andreas

+0

男人,這個問題似乎今天已經結束。這是[第三](http://stackoverflow.com/questions/42026750/jquery-readless-toogle-function/42026876#42026876)或[第四](http://stackoverflow.com/questions/42025444/jquery-not -selecting-element/42025520#comment71225022_42025520)僅在過去一個小時。 – Santi

回答

4
$(".ticButton").click(function() { 
    alert("you won"); 
}); 

此添加一個事件偵聽到所有當前存在的元素(元素現有當頁面最初加載的)。之後添加元素,這就是爲什麼沒有發生。

.on()這樣

$(document).on("click", ".ticButton", function() { 
    alert("you won"); 
});