【问题标题】:Why is this setTimeout method not working? [duplicate]为什么这个 setTimeout 方法不起作用? [复制]
【发布时间】:2017-11-02 01:48:37
【问题描述】:

我正在尝试使用 setTimeout() 方法来使用 jQuery 更改一些 CSS 属性,但我的方法不起作用。当函数应该被执行时,我不断收到“脚本错误”。代码编辑器不是为 jQuery 量身定制的,所以这可能就是我要得到的全部内容。我已将原因缩小到具体的 setTimeout 关键字,其中的代码块不会导致错误。我环顾四周,似乎没有其他人有我目前的问题。那怎么了?

else{//cards do NOT match
    $(this).css("backgroundColor", "#ff6666");
    $(cardId).css("backgroundColor", "#ff6666");
    setTimeout(function(){
       $(cardId).children().hide();
       $(cardId).css("backgroundColor", "white");
       $(this).children().hide();
       $(this).css("backgroundColor", "white");
    }, 1500);
}

【问题讨论】:

  • console.log(this)

标签: javascript jquery html css settimeout


【解决方案1】:

您的 this 关键字不正确。您可以使用 lambda 来不更改上下文。或者您可以在变量中设置“this”。

else {//cards do NOT match
    $(this).css("backgroundColor", "#ff6666");
    $(cardId).css("backgroundColor", "#ff6666");
    setTimeout(() => {
       $(cardId).children().hide();
       $(cardId).css("backgroundColor", "white");
       $(this).children().hide();
       $(this).css("backgroundColor", "white");
    }, 1500);
}

var self = this;
else {//cards do NOT match
    $(this).css("backgroundColor", "#ff6666");
    $(cardId).css("backgroundColor", "#ff6666");
    setTimeout(function(){
       $(cardId).children().hide();
       $(cardId).css("backgroundColor", "white");
       $(self).children().hide();
       $(self).css("backgroundColor", "white");
    }, 1500);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2011-01-03
    • 2018-08-08
    • 2015-10-05
    • 2015-07-08
    相关资源
    最近更新 更多