报错代码
获取html dom,然后遍历dom时,报错 tabList.forEach is not a function
var tabList = document.querySelectorAll('.mui-tab-item');
tabList.forEach(function(tabItem){
tabItem.classList.remove('mui-active');
if(tabItem.getAttribute('href') === activeUrl){
tabItem.classList.add('mui-active');
}
})
解决办法
加上一行代码
tabList = Array.from(tabList);
var tabList = document.querySelectorAll('.mui-tab-item');
tabList = Array.from(tabList);
tabList.forEach(function(tabItem){
tabItem.classList.remove('mui-active');
if(tabItem.getAttribute('href') === activeUrl){
tabItem.classList.add('mui-active');
}
})
Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。 将类数组对象转换为真正数组

在使用JavaScript处理DOM元素时遇到'forEach is not a function'的错误,原因是querySelectorAll返回的是一个NodeList对象,而非真正的数组。解决方法是通过Array.from()将NodeList转换为数组,然后再使用forEach方法。例如:`tabList=Array.from(tabList);`之后,tabList就可以正常遍历了。这个技巧在前端开发中处理类数组对象时非常实用。
601

被折叠的 条评论
为什么被折叠?



