我正在尝试通过编写井字游戏来练习 JS。到目前为止,这是我的代码:
$(document).ready(function() {
var turn = "X";
$("td").on("click", function() {
updateTile();
});
function updateTile() {
if ($(this).html() == "") {
$(this).html("<h1>" + turn + "</h1>");
updateTurn();
}
}
function updateTurn() {
if (turn == "X") {
turn = "O";
}
else if (turn == "O") {
turn = "X";
}
}
});
它不工作。我的调试使我相信 updateTile()
中的 $(this)
并不是指 $(this)
当 td
被点击。如果是这样,那是为什么呢? $("td")
是调用 updateTile()
的对象,因此 $(this)
不应引用 td
元素?
最佳答案
您正在调用匿名函数而不是您自己的函数。
像这样绑定(bind)你的点击:
$("td").on("click", updateTile);
编辑:
OP 希望在点击时执行其他操作。
因此您可以使用 call 来使用“this”和匿名函数。
$("td").on("click", function() {
alert("Click");
updateTile.call(this);
});
关于javascript - $(this) 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23460264/