简体   繁体   English

如何使 javascript 中的 setTimeout 适用于定义的 function?

[英]How to make setTimeout in javascript work for a defined function?

This is my code:这是我的代码:

$(".btn").click(function() {
  var userChosenColor = $(this).attr("id");
  animatePress(userChosenColor);
})

function animatePress(currentColor) {
  $("." + currentColor).addClass("pressed");
}

setTimeout(animatePress,2000);

So when I press the button on my website, the "pressed" class is applied (to make it darker) but the setTimeout doesn't work to make it revert back to its original colour.因此,当我按下我网站上的按钮时,会应用“按下”的 class(使其更暗),但 setTimeout 无法使其恢复为原始颜色。 I followed the layout for the functions carefully so I don't know why it's not working.我仔细遵循了功能的布局,所以我不知道为什么它不起作用。 Thanks in advance提前致谢

Edit: This is my jquery script in my HTML, could it be because of that?编辑:这是我的 HTML 中的 jquery 脚本,可能是因为这个吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-8"></script>

This should work:这应该有效:

$(".btn").click(function() {
    var userChosenColor = $(this).attr("id");
    animatePress(userChosenColor);
    setTimeout(() => animatePress(userChosenColor),2000);
})

function animatePress(currentColor) {
  $("." + currentColor).toggleClass("pressed");
}

You setTimeout is outside of the click which will not execute like that as its does not know where the userChoosenColor is:setTimeout在单击之外,不会像那样执行,因为它不知道userChoosenColor在哪里:

Try this code should just work fine.试试这个代码应该可以正常工作。

 $(".btn").click(function() { var userChosenColor = $(this).attr("id"); setTimeout(function() { animatePress(userChosenColor) }, 2000); }) function animatePress(currentColor) { $("." + currentColor).toggleClass("pressed"); console.log('I am Called') }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="btn">Click Me</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM