2017-02-03 39 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"); 
});