JavaScript遍历数组修改HTML input样式开发Wordle的问题排查
解决方案
问题原因
- 你定义
rowIndex1时直接写id作为变量的写法不是标准DOM操作方式,兼容性极差,且如果JS代码在页面DOM渲染前执行,数组里存的全是undefined,根本拿不到输入框元素,自然无法修改样式。 - HTML存在笔误:后4个输入框的
type属性错写为text.css,会导致输入框渲染和行为异常。 - 校验逻辑存在本质错误:你直接将DOM元素对象和答案字符串的字符做比对,二者数据类型完全不同,永远不会匹配成功;且没有读取输入框的实际输入值。
修复步骤
1. 修正HTML笔误
将所有输入框的type属性统一改为text,修正后的行代码如下:
<section id="row1"> <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup="jump001(this, 'square2')" id="square1"> <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup="jump001(this, 'square3')" id="square2"> <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup="jump001(this, 'square4')" id="square3"> <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup="jump001(this, 'square5')" id="square4"> <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup="jump001(this, 'square6')" id="square5"> <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup="jump001(this, 'square1')" id="square6"> </section>
2. 正确初始化元素数组
必须等页面DOM渲染完成后,通过标准DOM API获取每个输入框元素存入数组,不要直接用id当变量用:
// 等DOM全部加载完成再执行初始化 document.addEventListener('DOMContentLoaded', () => { // 逐个获取输入框元素存入数组 const rowIndex1 = [ document.getElementById('square1'), document.getElementById('square2'), document.getElementById('square3'), document.getElementById('square4'), document.getElementById('square5'), document.getElementById('square6') ] const answer = "shorts" // 示例:在最后一个输入框按回车时触发校验 rowIndex1[5].addEventListener('keydown', (e) => { if (e.key === 'Enter') checkWord(rowIndex1, answer) }) }) // 校验逻辑 function checkWord(inputList, answer) { // 统计答案中每个字母的剩余可匹配次数,避免重复字母匹配错误 const charCount = {} for (const c of answer) charCount[c] = (charCount[c] || 0) + 1 // 第一轮:匹配位置完全正确的字符,标绿色 for (let i = 0; i < inputList.length; i++) { const currentChar = inputList[i].value.trim().toLowerCase() // 先重置背景为灰色 inputList[i].style.backgroundColor = '#787c7e' if (currentChar === answer[i]) { inputList[i].style.backgroundColor = '#6aaa64' charCount[currentChar]-- } } // 第二轮:匹配字母存在但位置错误的字符,标黄色 for (let i = 0; i < inputList.length; i++) { const currentChar = inputList[i].value.trim().toLowerCase() if (inputList[i].style.backgroundColor === 'rgb(106, 170, 100)') continue // 已经是绿色的跳过 if (charCount[currentChar] && charCount[currentChar] > 0) { inputList[i].style.backgroundColor = '#c9b458' charCount[currentChar]-- } } }
关键说明
- 数组里存通过
getElementById获取到的DOM对象后,遍历数组直接修改元素的.style属性即可生效,不需要每次单独选元素。 - 输入框的用户输入内容存在元素的
.value属性里,必须读取这个值才能和答案做比对。 - 你之前写的嵌套循环逻辑会导致重复字母匹配错误,比如答案只有1个
s时,输入两个s会被错误标记,用字母计数的两次遍历写法和原版Wordle规则一致。
内容的提问来源于stack exchange,提问作者jeff jifferjay
相关产品推荐
相关产品推荐

