You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:45:04