我使用 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")
单击函数将“clicked”一词记录到控制台,但当我单击一个时从未发生过这种情况。
我已经尝试在 $(document).ready(function(){})
中包装点击函数,但它仍然不起作用。
最佳答案
你需要使用
$(document).on('click', '.tile', function() {
事件处理程序只绑定(bind)到当前选中的元素;它们必须在您的代码调用 .on() 时存在于页面上。为确保元素存在并可供选择,请在页面上 HTML 标记中的元素的文档就绪处理程序内执行事件绑定(bind)。如果新的 HTML 被注入(inject)到页面中,选择元素并在新的 HTML 被放入页面后附加事件处理程序。
我对您的 HTML 进行了更改并对其进行了测试并按预期工作。干杯!
关于javascript - 点击不注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384254/