当我尝试将 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>');
}
}
}
最佳答案
下面的代码可以正常编译,并且我已经添加了内联注释。
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>');
}
}
关于javascript - 当我尝试将 typescript 代码编译为javascript时,得到**类型 'NodeListOf<Element>'不是数组类型或字符串类型**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42383285/