javascript - 如何将此(jQuery 选择器)传递给 setTimeout() 函数?
问题描述
这按预期工作:
$('.lock').click(function() {
$('.fa-lock', this).addClass('fa-flip');
$('.fa-unlock', this).addClass('fa-flip');
setTimeout(function() {
$('.fa-lock').css('color', 'rgba(0, 0, 0, 0)');
$('.fa-unlock').css('color', 'green');
}, 600);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" rel="stylesheet" />
<style>
@keyframes halfflip {
to {
transform: rotateY(360deg);
}
}
.fa-flip {
animation-name: halfflip;
animation-timing-function: ease-in-out;
}
</style>
<div class="fa-5x fa-stack lock">
<i class="fas fa-unlock fa-stack-1x" style="--fa-animation-duration: 4s; --fa-animation-iteration-count: 1; color: transparent; animation-fill-mode: forwards; --fa-animation-delay:-2s"></i>
<i class="fas fa-lock fa-stack-1x" style="--fa-animation-duration: 4s; --fa-animation-iteration-count: 1; color: red; animation-fill-mode: forwards; --fa-animation-delay:-2s"></i>
</div>
但这不会:
$('.lock').click(function() {
$('.fa-lock', this).addClass('fa-flip');
$('.fa-unlock', this).addClass('fa-flip');
setTimeout(function() {
$('.fa-lock', this).css('color', 'rgba(0, 0, 0, 0)');
$('.fa-unlock', this).css('color', 'green');
}, 600);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" rel="stylesheet" />
<style>
@keyframes halfflip {
to {
transform: rotateY(360deg);
}
}
.fa-flip {
animation-name: halfflip;
animation-timing-function: ease-in-out;
}
</style>
<div class="fa-5x fa-stack lock">
<i class="fas fa-unlock fa-stack-1x" style="--fa-animation-duration: 4s; --fa-animation-iteration-count: 1; color: transparent; animation-fill-mode: forwards; --fa-animation-delay:-2s"></i>
<i class="fas fa-lock fa-stack-1x" style="--fa-animation-duration: 4s; --fa-animation-iteration-count: 1; color: red; animation-fill-mode: forwards; --fa-animation-delay:-2s"></i>
</div>
如何在不声明包含 jQuery 选择器的变量的情况下正确传递this
给函数?setTimeout()
添加“更多细节”。添加“更多细节”。添加“更多细节”。添加“更多细节”。添加“更多细节”。
解决方案
用这个替换你的代码
$('.lock').click(function() {
$('.fa-lock', this).addClass('fa-flip');
$('.fa-unlock', this).addClass('fa-flip');
setTimeout(()=>{
$('.fa-lock', this).css('color', 'rgba(0, 0, 0, 0)');
$('.fa-unlock', this).css('color', 'green');
}, 600);
});
这个工作而不是另一个工作的原因是,箭头函数this
在其范围内使用父范围,而用function
关键字定义的函数this
在其范围内初始化其自己的实例
推荐阅读
- android - 无法为 CameraX Preview 和 ImageAnalysis 设置自定义分辨率
- algorithm - 多边形算法中的多边形
- swift - DispatchWorkItem 如何取消递归过程?
- javascript - Javascript 自动触发按钮提交带有动态操作链接的 php 表单
- postgresql - 如何使用自定义类型在 postgres(数组)类型中创建类型
- sql - SQL Server SMO 查询性能(2014 与 2017)
- ios - 使用电话号码在 IOS 上通过 Firebase 进行身份验证
- javascript - 无法使用 jQuery 获取 .attr('aria-controls')
- sql - Django 中的多个数据库 - MSSQL
- bukkit - 持久数据容器未保存到块