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

修改id为buttons的ul列表项背景色时触发TypeError错误求助

问题描述

我想修改id为buttons的无序列表中所有列表元素的background-color,点击列表项时让所有按钮变色,但出现如下错误:

main.js:135 Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor')
at buttonClicked (main.js:135:48)
at HTMLLIElement. (main.js:65:72)

相关代码如下:

JavaScript代码

let buttons = document.querySelector("#buttons").querySelectorAll("li");
for ( let elements of buttons ) {
  elements.addEventListener( "click", function( event ) {buttonClicked( event )} );
}

function buttonClicked( event ) {
  let buttons = document.querySelector("#buttons").querySelectorAll("li");
  for ( let element in buttons ) {
    buttons[element].style.backgroundColor = "black";
  }
}

CSS代码

#buttons li {
    list-style-type: none;
    border-radius: 5px;
    background-color: rgba( 0, 57, 116, 0.5 );
    color: rgba( 255, 255, 255, 1);
    padding: 20px;
    margin: 10px;
}

#buttons li:hover {
    background-color: rgba( 0, 57, 116, 0.8 );
    cursor: pointer;
}

#buttons li:active {
    color: rgba( 150, 150, 150, 1); 
}

HTML代码

<ul id="buttons">
  <li id="round-view">Drag and drop</li>
  <li id="demo-view">Demo mode</li>
  <li id="home-view">View home</li>
  <li id="casing-view">Show/Hide Casing</li>
</ul>

问题原因及解决方法

错误原因

你在buttonClicked函数里用了for...in循环遍历querySelectorAll返回的NodeList对象,但for...in会遍历对象的所有可枚举属性——除了列表元素的索引外,还会遍历NodeList自带的属性(比如length、item方法)。当循环到这些非索引属性时,buttons[element]会返回undefined,自然无法设置style.backgroundColor,导致报错。

解决方法

用以下任意一种方式替换for...in循环即可:

方法1:使用for...of循环(推荐,和绑定事件的循环方式一致)

function buttonClicked( event ) {
  let buttons = document.querySelector("#buttons").querySelectorAll("li");
  for ( let element of buttons ) {
    element.style.backgroundColor = "black";
  }
}

方法2:使用普通for循环

function buttonClicked( event ) {
  let buttons = document.querySelector("#buttons").querySelectorAll("li");
  for ( let i = 0; i < buttons.length; i++ ) {
    buttons[i].style.backgroundColor = "black";
  }
}

方法3:使用NodeList的forEach方法

function buttonClicked( event ) {
  let buttons = document.querySelector("#buttons").querySelectorAll("li");
  buttons.forEach(element => {
    element.style.backgroundColor = "black";
  });
}

内容的提问来源于stack exchange,提问作者stoex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:01:02