在仍未在 dom 中的元素上添加点击事件
我必须在锚元素上添加单击事件,该元素可以稍后加载我知道在 javascript 中我可以这样做。
document.addEventListener('click', function(e){
if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
//do something
}
});
但我需要在有角度的打字稿中做,我正在尝试这样,
document.addEventListener("click", function (e) {
try {
let id = e.target && (e.target as HTMLAnchorElement).id;
console.log(id)
if (id == 'lnkCheck') {
alert('Hi');
}
} catch (error) {
}
})
但它不起作用,另外我如何检查目标是否是锚标记
有任何帮助,非常感谢,
更新
上面的代码唯一的问题是我点击了错误的地方
谢谢
I have to add click event on a anchor element that can load later I know in javascript I can do like this.
document.addEventListener('click', function(e){
if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
//do something
}
});
But I need to do In Typescript in angular and I am trying like this,
document.addEventListener("click", function (e) {
try {
let id = e.target && (e.target as HTMLAnchorElement).id;
console.log(id)
if (id == 'lnkCheck') {
alert('Hi');
}
} catch (error) {
}
})
But its not working, also How can I check if the target is an anchor tag
any help, highly appreciated,
UPDATE
the above code is working only issue was I was clicking on wrong place
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确定该元素将位于具有给定 id 的 DOM 中,那么可以借助组件中的 AfterViewInit 接口来实现此操作,如下所示。
If you are sure that element will be in the DOM with given id then this thing can be implemented with the help of AfterViewInit interface in the component something like this.
这是你想要的吗?
Is this what you want?