[英]How to make setTimeout in javascript work for a defined function?
这是我的代码:
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
})
function animatePress(currentColor) {
$("." + currentColor).addClass("pressed");
}
setTimeout(animatePress,2000);
因此,当我按下我网站上的按钮时,会应用“按下”的 class(使其更暗),但 setTimeout 无法使其恢复为原始颜色。 我仔细遵循了功能的布局,所以我不知道为什么它不起作用。 提前致谢
编辑:这是我的 HTML 中的 jquery 脚本,可能是因为这个吗?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-8"></script>
这应该有效:
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
setTimeout(() => animatePress(userChosenColor),2000);
})
function animatePress(currentColor) {
$("." + currentColor).toggleClass("pressed");
}
您setTimeout
在单击之外,不会像那样执行,因为它不知道userChoosenColor
在哪里:
试试这个代码应该可以正常工作。
$(".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.