JavaScript下拉选择器颜色切换功能失效求助(CS50课程代码)
问题原因及修复方案
错误点分析
你的JavaScript代码里存在语法错误:
document.querySelector("#hello").getElementsByClassName.color = this.value;
getElementsByClassName是用于获取指定类名元素集合的方法,此处完全不需要调用它,且你错误地将其当作属性来访问.color,这直接导致颜色设置逻辑失效。
修复后的代码
只需把错误代码改为直接设置元素的style.color属性即可:
修复后的JavaScript代码
document.addEventListener("DOMContentLoaded", () => { document.querySelector("select").onchange = function () { document.querySelector("#hello").style.color = this.value; }; });
完整可运行HTML代码
<html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script> document.addEventListener("DOMContentLoaded", () => { document.querySelector("select").onchange = function () { document.querySelector("#hello").style.color = this.value; }; }); </script> </head> <body> <h1 id="hello" class="heading">hello</h1> <select> <option value="black">Black</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> </select> <br /> <br /> </body> </html>
效果验证
修复完成后,切换下拉选择器的选项,hello文字的颜色会同步变为选中的颜色,功能即可正常工作。
内容的提问来源于stack exchange,提问作者Adam Durrant
相关产品推荐
相关产品推荐

