我尝试获取所有在打字稿中都有类名称的要素,并需要检查每个元素的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();
     }
   }
 }


但是在我的if条件行中,我在数据Property 'data' dose not exist on type HTMLElement上收到此错误

我做错了吗?

最佳答案

因为data()是jQuery的一种获取数据属性的方法。您应该使用dataset属性来修改和读取数据属性。另外请记住,您只能在数据属性中存储字符串值:

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


另一种选择是使用getAttribute('data-*')获取值或使用setAttribute('data-*', value)设置值。

您可以在MDN page中查看有关如何正确使用数据属性的教程。

关于javascript - Typescript:属性“数据”在HTMLElement类型上不存在,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48945324/

10-12 12:33
查看更多