点击不注册

时间:2018-11-19 23:45:11

标签: javascript jquery

我使用Jquery添加了一堆按钮,它们都在同一类中,并且我试图让它们在单击时做一些事情。我现在为他们提供了一个简单的单击功能,只需将“单击”一词记录到控制台中,但它没有注册我的任何单击。这是我的代码:

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Minesweeper</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="dimensions">
        Width:  <input type="Width" id="width"><br/>
        Height: <input type="Height" id="height"><br/>
        <button type="button" id="new-game" onclick="newGame()">Create</button>
    </div>
    <div id="board"></div>
</body>
</html>

Javascript:

function newGame() {
    var cols = $("#width").val();
    var rows = $("#height").val();

    if (cols < 8 || rows < 8) {
        return;
    }else if (cols > 40 || rows > 30) {
        return;
    }
    boardClear();
    possibleBombs = (rows * cols) - 1;
    numBombs = 0;
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= cols; j++) {
            if (numBombs < possibleBombs) {
                q = Math.floor(Math.random() * 2);
                if (q == 0) {
                    numBombs += 1;
                }
                $("#board").append('<button type="button" class="tile" data-row = ' + i + 'data-col = ' + j + 'data-contains = ' + q + '></button>');
            } 
            else {
                $("#board").append('<button type="button" class="tile" data-row = ' + i + 'data-col = ' + j + 'data-contains = 1 ></button>');
            }
        }
        $("#board").append("<br/>");
    }
    $(".tile").width(100/cols);
    $(".tile").height(100/rows);
    console.log("bombs: " + numBombs, "possible: " + possibleBombs);
}

$(".tile").on('click', function() {
    $(this).css("color", "black");
    console.log("clicked");
});

function boardClear() {
    $("#board").empty();
}

您可以看到我的$(".tile") on click功能在控制台上记录了“ clicked”一词,但是当我单击它时却从未发生。

我尝试将点击功能包装在$(document).ready(function(){})中,但仍然无法正常工作。

1 个答案:

答案 0 :(得分:2)

您需要使用

$(document).on('click', '.tile', function() {

事件处理程序仅绑定到当前选定的元素;当您的代码调用.on()时,它们必须存在于页面上。为了确保元素存在并可以选择,请在文档就绪处理程序内对页面上HTML标记中的元素执行事件绑定。如果要在页面中注入新的HTML,则在将新的HTML放入页面后,选择元素并附加事件处理程序。

我在您的HTML中进行了更改,并对其进行了测试,并且可以正常工作。干杯!

相关问题