JS中EventListener仅触发一次?按钮切换文字颜色失效
代码存在的核心问题
- 条件判断使用了赋值运算符而非相等判断运算符:原代码
if (header.style.color = "red")中的=是赋值操作,每次执行到这行代码时,都会强制把header.style.color设置为"red",赋值操作返回的字符串为真值,因此判断条件永远成立,只会触发该分支的执行逻辑,else分支完全不会被触发。 - 变量名拼写错误:
else if分支中写的是head.style.color,但你之前定义的DOM元素引用变量为header,此处拼写错误会触发未定义变量报错,导致分支逻辑直接失效。 - 样式读取逻辑不匹配:你将初始红色样式写在了内部CSS规则中,而
element.style.color仅能读取元素的内联样式,无法获取CSS规则中定义的样式值,初始状态下该属性值为空字符串,无法正确判断当前元素的实际颜色状态。
修正后的可运行实现
HTML
<h1 id="header"> Here's some text </h1> <button id="button"> Change the Color </button>
CSS
#header { color: red; }
JavaScript
const header = document.getElementById("header"); const button = document.getElementById("button"); button.addEventListener("click", function() { // 通过getComputedStyle获取元素实际渲染的样式,不受样式书写位置影响 // 注意:浏览器返回的颜色值统一为rgb格式 const currentColor = getComputedStyle(header).color; // 使用===做严格相等判断,替换原有的赋值操作 if (currentColor === "rgb(255, 0, 0)") { header.style.color = "blue"; } else { header.style.color = "red"; } })
补充说明:如果不想依赖颜色值做判断,也可以用自定义状态变量简化逻辑,避免样式格式匹配的问题,示例如下:
const header = document.getElementById("header"); const button = document.getElementById("button"); let currentColorIsRed = true; // 维护颜色状态变量 button.addEventListener("click", function() { currentColorIsRed = !currentColorIsRed; // 每次点击切换状态 header.style.color = currentColorIsRed ? "red" : "blue"; })
内容的提问来源于stack exchange,提问作者Kirk Snyder Jr.
相关产品推荐
相关产品推荐

