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

标签 javascript typescript ionic-framework ionic3

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

相关文章:

执行代码时Javascript运行时错误

jquery - 如何将 jQuery 的 $.post() 方法与 async/await 和 typescript 一起使用

android - ionic 3 native : File : {code: 5, 消息: "ENCODING_ERR"}

node.js - ionic - events.js :160 throw er;//Unhandled 'error' event

javascript - 什么被认为是在 Node 模块内共享 "global"变量的好方法?

php - 如何删除所有 div 标签,但不删除其内容? (使用 contenteditable ="true",HTML5)

javascript - 有没有办法在没有样式的情况下使用 Angular Material?

reactjs - 导出接口(interface)和类扩展 Component/PureComponent

javascript - 如何检查组件子组件是否有子组件?

android - Android 目标 API 级别 28+ 后出现错误 “Google is not defined””