循环生成16-30偶数字号选项异常:仅显示16-23问题排查
问题:Select控件未正确生成16-30的偶数字号选项
需要实现程序为fontSizeBox select控件添加16到30(含30)的偶数字号选项,但实际运行后控件仅显示16到23的数字,不符合预期。
原代码
window.onload = function() { let fontSizeBox = document.createElement("select"); fontSizeBox.name = "fontSize-box"; document.body.prepend(fontSizeBox); let fontSizeBoxLabel = document.createElement("label"); fontSizeBoxLabel.appendChild(document.createTextNode("Choose the font size :")); fontSizeBox.before(fontSizeBoxLabel); for (let i = 16; i <= 30; i += 2) { fontSizeBox.appendChild(document.createElement("option")); } Array.from(fontSizeBox); /* The above code will make the fontSizeBox an array so I can iterate over it using the loop */ for (let i = 0; i <= 7; i++) { fontSizeBox[i].innerHTML = i + 16; /* The following code won't work without the number constructor because I tried this code in the console and here is the output: typeof fontSizeBox[0].innerHTML; >> 'string' */ if ((Number(fontSizeBox[i].innerHTML) % 2) !== 0) { continue; } } }
<title>Document</title>
错误分析
- 无效的数组转换:
Array.from(fontSizeBox)仅返回新数组,但未赋值给变量,原fontSizeBox仍为DOM元素,这行代码无实际作用。 - 错误的赋值逻辑:第二个循环中
i + 16生成的是16到23的连续数字(i从0到7),而非目标偶数值。后续continue仅跳过奇数的后续处理,但已经将奇数内容写入option,导致最终显示16-23的数字。 - 冗余的循环拆分:完全不需要分两次循环处理,一次循环即可完成option的创建与内容设置。
修正方案
直接在创建option的循环中设置其显示文本与值,一步完成需求:
window.onload = function() { let fontSizeBox = document.createElement("select"); fontSizeBox.name = "fontSize-box"; document.body.prepend(fontSizeBox); let fontSizeBoxLabel = document.createElement("label"); fontSizeBoxLabel.textContent = "Choose the font size :"; fontSizeBox.before(fontSizeBoxLabel); // 一次循环生成所有偶数字号选项 for (let i = 16; i <= 30; i += 2) { let option = document.createElement("option"); option.textContent = i; // 设置显示文本 option.value = i; // 设置选项值(可选,建议添加) fontSizeBox.appendChild(option); } }
说明
- 使用
textContent替代innerHTML更安全,避免潜在XSS风险,且更适合纯文本内容设置。 - 直接在创建option时赋值,逻辑清晰,避免额外循环带来的错误。
- 生成的选项为16、18、20、22、24、26、28、30,完全符合需求。
内容的提问来源于stack exchange,提问作者Mohammed
相关产品推荐
相关产品推荐

