javascript - $(this) 出现问题

标签 javascript jquery this

我正在尝试通过编写井字游戏来练习 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/

相关文章:

javascript - Twitter Bootstrap 下拉菜单不出现

javascript - 查找嵌套数组的索引

javascript - mvc View 中的网格行选择

jquery - 将变量传递给 window.location href

javascript - d3.select(this) 适用于鼠标悬停,但不适用于鼠标悬停时调用的函数

javascript - 无法根据下拉列表中选定的值过滤数据表数据

javascript - 我如何使用 javascript 在 IE7、IE8、Safari 和其他支持的浏览器中播放 .Wav 声音

jQuery 仅在 <h2> block 而不是背景中隐藏文本

javascript - 难以确定 JS/jQuery 代码中的 'this' 所指的内容

javascript - 如何在 jquery 中保留 'this' 的上下文