JavaScript导航栏出现TypeError: 'undefined' is not an object报错求助
错误原因
- 所有调用
ClassList的地方拼写错误,DOM元素的类名操作API是小写开头的classList,JS大小写敏感,写错后该属性值为undefined,调用方法就会抛出对应错误 classList判断类名是否存在的方法是contains不是container,拼写错误导致方法不存在handleIndicator函数内遍历items的forEach回调参数命名为el,但函数体内实际用的是未定义的item变量,变量名不匹配导致item为undefined- 最后给文字颜色赋值时调用了不存在的
Attributes()方法,获取自定义属性值统一用getAttribute()即可
修正后代码
var indicator = document.querySelector('.indicator'); var items = document.querySelectorAll('.nav-item'); function handleIndicator(el) { items.forEach(function(item) { item.classList.remove('active'); item.removeAttribute('style'); }); indicator.style.width = "".concat(el.offsetWidth, "px"); indicator.style.left = "".concat(el.offsetLeft, "px"); indicator.style.backgroundColor = el.getAttribute('active-color'); el.classList.add('active'); el.style.color = el.getAttribute('active-color'); } items.forEach(function(item, index) { item.addEventListener('click', function(e) { handleIndicator(e.target); }); item.classList.contains('active') && handleIndicator(item); });
内容的提问来源于stack exchange,提问作者NoobNoob
相关产品推荐
相关产品推荐

