Javascript 如何在setTimeout内更改ionic3页面属性?

Javascript 如何在setTimeout内更改ionic3页面属性?,javascript,typescript,ionic-framework,ionic3,Javascript,Typescript,Ionic Framework,Ionic3,我需要在几秒钟后更改给定属性的值,但是使用setTimeout无法更改class属性 let answer = document.getElementById(id); answer.style.background = "#00a232"; this.activated = true; setTimeout(function(){ answer.style.background = "#97a8c6"; //this.activate

我需要在几秒钟后更改给定属性的值,但是使用setTimeout无法更改class属性

    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属性?

您的问题是范围界定

你试过使用胖箭头符号吗?这将更改此的范围

你有:

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);

从:箭头函数中捕获
函数的创建位置,而不是调用位置

您的问题是确定范围

你试过使用胖箭头符号吗?这将更改此的范围

你有:

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);
从:箭头函数捕获创建函数的
位置,而不是调用函数的位置