当我尝试将typescript代码编译为javascript时,获取** Type'NodeListOf <element>'不是数组类型或字符串类型**

时间:2017-02-22 05:19:23

标签: javascript html typescript

当我尝试将打字稿代码编译成javascript时,获取类型'NodeListOf'不是数组类型或字符串类型

if (query.length) {                                              
  var regex = new RegExp("(" + query + ")", "gm"); 
  var li = document.querySelectorAll("#id li"); //error                 
    for (var Element of li){                                   
      Element.innerHTML = Element.innerHTML.replace(regex, '<span class="classname">$1</span>'); 
    }
  }
}

3 个答案:

答案 0 :(得分:0)

以下编译正常,我已在内联添加评论。

let query = '';
if (query.length) {
    var pattern = new RegExp("(" + query + ")", "gim");
    var li: NodeListOf<Element> = document.querySelectorAll("#test li");
    // ES5 does not allow TS iteration of NodeListOf<Element> nor use of Array.from 
    // so it is necessary to loop over it manually.
    // Note that Element is an existing type which caused a conflict with "(var Element of list)".
    // It was necessary to rename Element to element.
    for (let i = 0; i < li.length; i++) {
        let element = li[i];
        element.innerHTML = element.innerHTML.replace(pattern, '<span class="target">$1</span>');
    }
}

答案 1 :(得分:0)

这也可以:

let elements: any = document.querySelectorAll(".class");
for(let ele of elements) {
     // do stuff
}

答案 2 :(得分:-1)

试试这个......会解决问题。

if (query.length) {                                              
  var pattern = new RegExp("(" + query + ")", "gim"); 
  var li = document.querySelectorAll("#test li");                 
   for (var Element of <any> li){                                   
      Element.innerHTML = Element.innerHTML.replace(pattern, '<span class="target">$1</span>'); 
    }
}