我需要在几秒钟后更改给定属性的值,但使用 setTimeout 无法更改类属性。
let answer = document.getElementById(id);
answer.style.background = "#00a232";
this.activated = true;
setTimeout(function(){
answer.style.background = "#97a8c6";
//this.activated = false
}, 1500);
我注释了属性更改的行,因为它不起作用,因为它是一个函数并且其中没有这样的属性。
我试图传递一个类方法来进行此更改:
let answer = document.getElementById(id);
answer.style.background = "#00a232";
this.activated = true;
setTimeout(this.activate, 1500);
用写法如下:
activate(answer){
answer.style.background = "#97a8c6";
this.activated = false
}
但是我不能传递参数,而且如果通过setTimeout()调用该方法,属性也不会被修改。
setTimeout()时间过去后如何修改class属性?
最佳答案
您的问题是范围界定。
您是否尝试过使用粗箭头表示法?这改变了 this
的范围。
你有:
setTimeout(function(){
answer.style.background = "#97a8c6";
this.activated = false // this is in the scope of the function
}, 1500);
你试过吗:
setTimeout(() => {
answer.style.background = "#97a8c6";
this.activated = false // this is in the same scope where the function was created
}, 1500);
来自documentation : 箭头函数捕获创建函数的 this
而不是调用函数的地方
关于javascript - 如何在 setTimeout 内更改 ionic3 页面属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619462/