我想知道当任何 div
的 innerHtml
属性发生更改并且该 div
的 DOM 树为完全加载到内存中。
我想在该事件触发后调用以下函数。我想删除以下函数中的 setTimeout()
hack,因为它有时可能会失败。
private registerEventListenersForLink() {
let _self = this;
setTimeout(function () {
var AElemList = document.querySelectorAll('.appmedia-content-wrapper a');
for (let i = 0; i < AElemList.length; i++) {
AElemList[i].addEventListener("click", function (event) {
event.preventDefault();
event.stopPropagation();
var url = event.target["href"];
if (url && url.trim() != '') {
_self.utilService.openUrlExternaly(url);
}
});
}
}, 80);
}
我找到了与上述问题相关的以下链接,但我没有从中得到任何想法:
Event to determine when innerHTML has loaded
https://www.w3.org/html/wg/spec/apis-in-html-documents.html#dom-innerhtml
最佳答案
我解决了我的问题。我已经实现了如下指令,它的效果非常好。感谢 Rory McCrossan 向我指出 MutationObserver api。
import { Directive, ElementRef } from '@angular/core';
import { UtilService } from '../../providers/util-service';
@Directive({
selector: '[external-links]' // Attribute selector
})
export class ExternalLinks {
private observer;
constructor(private elRef: ElementRef, public utilService: UtilService) {
}
ngAfterViewInit() {
var _self = this;
this.observer = new MutationObserver(mutations => {
mutations.forEach(function (mutation) {
if (mutation.type == 'childList') {
var AElemList = _self.elRef.nativeElement.querySelectorAll('a');
for (let i = 0; i < AElemList.length; i++) {
AElemList[i].addEventListener("click", function (event) {
event.preventDefault();
event.stopPropagation();
var url = event.target["href"];
if (url && url.trim() != '') {
_self.utilService.openUrlExternaly(url);
}
});
}
}
});
});
var config = { childList: true };
this.observer.observe(this.elRef.nativeElement, config);
}
}
关于javascript - 内部 html 在 DOM 树中完全渲染后会触发哪个事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42838921/