简体   繁体   English

Typescript:属性“数据”在HTMLElement类型上不存在

[英]Typescript : Property 'data' dose not exist on type HTMLElement

I try to get all elemets which have a class name in typescript and need to check something on data property of each element, this is what I came so far : 我尝试获取所有在打字稿中都有类名称的要素,并需要检查每个元素的data属性,这是我到目前为止的结果:

let getTopElements :NodeListOf<HTMLElement>  = document.querySelectorAll('.timeline-row');
var newArr: HTMLElement[] = Array.prototype.slice.call(getTopElements);

if (getTopElements){
  for (let element of newArr){
    if (element.data('options') && element.data('options').type === 'TOP')   {
       this.player.currentTime(element.data('options').end).pause();
     }
   }
 }

But in my if condition line, I get this error on data Property 'data' dose not exist on type HTMLElement 但是在我的if条件行中,我在data Property 'data' dose not exist on type HTMLElement上遇到此错误, Property 'data' dose not exist on type HTMLElement

Am i doing this wrong? 我做错了吗?

Because data() is a method from jQuery to get data attributes. 因为data()是jQuery的一种获取数据属性的方法。 You should use the dataset property to modify and read data attributes. 您应该使用dataset属性来修改和读取数据属性。 Also keep in mind that you can only store string values in a data attribute: 另外请记住,您只能在数据属性中存储字符串值:

 const data = element.dataset;
 data.optionsType = 'TOP';
 if (data.optionsType === 'TOP')   {
   this.player.currentTime(data.optionsEnd).pause();
 }

Another option would be to use getAttribute('data-*') to get the value or setAttribute('data-*', value) to set the value. 另一种选择是使用getAttribute('data-*')获取值或使用setAttribute('data-*', value)设置值。

You could have a look at the MDN page for a tutorial how to properly use data attributes. 您可以在MDN页面上查看有关如何正确使用数据属性的教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM