当前位置:   article > 正文

js循环报错:forEach is not a function_js foreach is not a function

js foreach is not a function

js循环报错:forEach is not a function

报错代码

获取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');
	}
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

解决办法

加上一行代码

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');
	}
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。 将类数组对象转换为真正数组

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/266029
推荐阅读
相关标签
  

闽ICP备14008679号