【问题标题】:How to change an ionic3 page attribute within a setTimeout?如何在 setTimeout 中更改 ionic3 页面属性?
【发布时间】:2019-02-11 13:19:08
【问题描述】:

我需要在几秒钟后更改给定属性的值,但使用 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属性?

【问题讨论】:

    标签: javascript typescript ionic-framework ionic3


    【解决方案1】:

    您的问题是范围界定。

    您是否尝试过使用粗箭头表示法?这改变了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 创建函数的位置而不是调用它的位置

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 2022-01-22
      • 2021-12-01
      • 2014-09-02
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多