javascript - 我怎样才能等到某些东西不为空然后运行该函数
问题描述
所以目前这个函数highlight
被调用,ngOnInit
但是被放入的文本DOM
需要一秒钟左右的时间才能写入DOM
.
因此,null
当函数运行时它会返回并期待那里的文本。我怎样才能让这个函数在document.getElementById('scrollable')
NOT时 === null
运行。
到目前为止,我让它运行的唯一方法是超时,800ms
但这并不好,因为有些人的互联网速度比其他人慢,所以如果互联网或计算机需要更长的时间来加载页面,就会导致问题。
我尝试了几种不同的方法,但都没有奏效。如果有人有任何好的建议,请随时告诉我。
highlight(words) {
const high = document.getElementById('scrollable');
const paragraph = high.innerHTML.split(' ');
}
}
目前使用 Angular 6。
HTML:https ://gist.github.com/ElAndy94/fa78b5b25a73716e2c32045c6c6be1ff
技术支持:https ://gist.github.com/ElAndy94/85950e0e84aad30a72d3b91faa7d6278
解决方案
我建议你看看Angular Component Life Cycle。您应该使用AfterViewInit
钩子来确保您的视图已初始化。
import { Component, AfterViewInit } from '@angular/core';
@Component({...})
export class MyOwnComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit() { // Here your view is checked and initialized.
this.highlight();
}
highlight(words) {
const high = document.getElementById('scrollable');
const paragraph = high.innerHTML.split(' ');
...
}
}
推荐阅读
- scala - 如何在我的示例中加入数据框?
- spring - 如何通过 Spring Social Facebook 注册新用户?
- cors - Rally Cors 问题
- c# - 使用 Linq 从 C# 中的字典中删除具有相同值数据的多个键
- python - 运行 Fuzzywuzzy 字符串匹配器脚本的问题
- typescript - Typescript 函数重载不适用于联合类型案例
- java - 在java中使用正确的数据结构返回数组中的最高元素
- android - Unity 视频播放器在 whatsapp 通知上崩溃
- ios - 当应用程序被杀死或未运行时,如何从 IOS 应用程序的推送通知中打开特定视图?
- sap - SAP Vora 1.4 工作者停止