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

JavaScript遍历数组修改内部input输入框颜色失效问题

问题原因

代码不生效的核心原因有两个:

  1. 定义square1~square6变量时,赋值取的是DOM元素的.value(也就是输入框里的文本内容,属于字符串类型),不是DOM元素本身。字符串没有style属性,自然无法通过数组索引调用样式修改方法。你直接指定元素操作时生效,是因为操作时直接获取了DOM元素对象,没有用到之前存了字符串值的变量。
  2. HTML里后4个输入框的type属性笔误写成了text.css,会导致输入框默认行为异常。
修复方法

按照以下步骤调整即可:

  • 首先修正HTML笔误,把所有错写的type="text.css"替换为type="text"。
  • 调整square系列变量的赋值逻辑,去掉末尾的.value,直接存储DOM元素对象,后续需要读取输入内容时再单独取.value属性即可。
  • 写全循环逻辑遍历数组修改样式。

修正后的参考代码

变量定义部分

// 存储DOM元素对象,不要加.value
const square1 = document.getElementById("square1");
const square2 = document.getElementById("square2");
const square3 = document.getElementById("square3");
const square4 = document.getElementById("square4");
const square5 = document.getElementById("square5");
const square6 = document.getElementById("square6");
const rowIndex1 = [square1, square2, square3, square4, square5, square6];

遍历修改样式部分

// 普通for循环实现
for (let i = 0; i < rowIndex1.length; i++) {
  rowIndex1[i].style.backgroundColor = 'green';
}

// 也可以用更简洁的forEach写法
rowIndex1.forEach(inputEl => {
  inputEl.style.backgroundColor = 'green';
})

补充:如果后续需要获取某个输入框的内容,直接调用对应元素的value属性即可,比如const firstInputVal = square1.value。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 06:12:59