【问题标题】:Run jQuery click function ONCE运行 jQuery 点击功能 ONCE
【发布时间】:2016-07-04 01:47:52
【问题描述】:

我无法让这个点击函数在每次 turnRound() 调用中运行一次。所以我把它放在一个 if 语句中,由于 humanMoved 变量为真,因此在一次执行后应该会被破坏。但是单击具有“square”类的元素仍会调用单击函数。 turnRound() 也只被调用一次。我在想这可能是humanMoved 的变量范围问题,或者我只是不明白.click()

function turnRound(c){
    humanMoved = false;
    if (c == "X" && humanMoved == false) {
        $(".square").click(function(){
            $(this).text(c);
            humanMoved = true;
        });
    }

【问题讨论】:

  • 使用one('click', fn);
  • humanMoved 在每次调用 turnRound() 时设置为 false。
  • 戴夫说了什么。您只需要将 humanMoved 变量移到 turnRound 函数之外。否则,它只会在每次点击时恢复为 false
  • 另外,if 语句应该在 click 回调中。

标签: javascript jquery


【解决方案1】:

而不是下面的代码:

$(".square").click(function(){
  $(this).text(c);
  humanMoved = true;
});

将其替换为.one():

$(".square").one("click", function(){
  $(this).text(c);
  humanMoved = true;
});

或者,您可以使用.off() 删除click 事件:

$(".square").click(function(){
  $(this).text(c);
  humanMoved = true;
  $(this).off("click");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2014-03-05
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多