类型“ EventTarget”缺少以下属性

时间:2020-06-09 10:50:32

标签: javascript reactjs typescript web

你好,我在TypeScript中有这段代码

 var btn  = document.getElementsByClassName("btn-up") as EventTarget;
 btn.addEventListener('click', (event) => {
 console.log('clickcc');
})

它把我抛出这个错误 *类型“ HTMLCollectionOf”缺少类型“ EventTarget”中的以下属性:addEventListener,dispatchEvent,removeEventListener *

请如何解决?

1 个答案:

答案 0 :(得分:3)

这将返回元素array,而不仅仅是单个元素:

document.getElementsByClassName("btn-up") as EventTarget

收件人:

document.getElementsByClassName("btn-up")[0] as EventTarget

工作演示:

Edit #SO-TS-EventTarget