追加后事件监听器不起作用

时间:2017-02-03 15:57:43

标签: javascript jquery html

最近我开始学习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>
	<title> Play </title>
	<script src="jquery-3.1.1.js"></script>
	<script src="behavior.js" type="text/Javascript"></script>
	<link href="style.css" rel = "stylesheet" type="text/CSS" />
     </head>
     <body>
	<h1> Welcome </h1>
	<button id="game"> play </button>
	
    </body>
    </html>

所以我的目的是,在点击播放(id =游戏)按钮后,应该会出现9个新按钮,点击其中任何一个后,应该提出警告说:你赢了。但是发生的情况是:出现9个新按钮后,单击它们时没有任何反应。 有什么建议? 我想提一下有一个关于事件监听器的问题,这在动态创建后不起作用,但是这个问题及其答案对我没有帮助。

1 个答案:

答案 0 :(得分:4)

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

这会向所有当前存在的元素添加事件侦听器(最初加载页面时存在的元素)。之后添加了您的元素,这就是没有任何反应的原因。

使用.on()声明您的活动

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