setTimeout 与 setInterval 中的 this
不论以后应用的this指向谁,在应用 setTimeout 或者 setInterval 中的 this 都会指向最外层对象,也就是window ,而应用箭头函数就能够让 this 持续指向上一层对象而不是最外层。
<body>
<buttn id='demo'>发送验证码</button>
</body>
<script type="text/javascript">
// jquery
// 从新发送验证码倒计时
$("#demo").click(functuin() {
// 给demo按钮增加disabled禁用属性,this指向button标签对象
$(this).addClass('disabled');
var time = 30;
// 想要在click中应用setTimeout, 一般写法setTimeout(function(){}, 1000),会让this指向window,导致不能应用$(this)去间接操作button
// 能够应用 _this = this 先把button对象拿进去,更简略的办法是应用箭头函数 (=>)
var interval= setInterval(() => {
if(condition){
// 去除定时器
clearInterval(interval);
$(this).removeClass('disabled');
$(this).attr('disabled', false);
$(this).test("从新发送");
return;
}
time--;
$(this).text('从新发送(' + time + 's)');
}, 1000)
})
</script>
发表回复