【问题标题】:EventListener Only Firing OnceEventListener 只触发一次
【发布时间】:2021-03-22 06:54:08
【问题描述】:

仍在学习 JS 的基础知识,现在使用 EventListeners。尝试制作一个来回更改文本颜色的按钮,但我认为我误解了该方法的性质,或者使用不正确。我不认为这是语法问题。

我有文本和按钮,都带有 ID。我为这两个元素创建了变量。我为按钮添加了一个事件监听器,并在函数中定义了 if else 语句。函数的“if”部分执行没有问题,但这就是它结束的地方。提前对格式表示抱歉,我不确定什么是最有意义的。谢谢!

这是 HTML:

<h1 id="header"> Here's some text </h1>

<button id="button"> Change the Color </button>

CSS:

#header {
    color: red;
  }

还有 JavaScript:

var header = document.getElementById("header");

var button = document.getElementById("button");

button.addEventListener("click", function() {

  if (header.style.color = "red")   

{header.style.color = "blue";} 

else if (head.style.color = "blue")
{header.style.color = "red";
  }
})

【问题讨论】:

  • 在第二个if 中将if (head.style... 替换为if (header.style,并使用=== 检查值是否相等。不是=,它只用于赋值

标签: javascript html addeventlistener event-listener


【解决方案1】:

在 JavaScript(和其他语言)中,您需要使用 == 来检查是否相等。

然而,在 JavaScript 中也有 ======严格相等 运算符,这意味着它不进行类型转换。那是什么意思?意思是:

"5" == 5 // true, since "5" as a number is equal to 5, the literal number

"5" === 5 // false, since a string cannot equal a number

因此,在您的 if 语句中,您应该使用 ===== 而不仅仅是 =

【讨论】:

  • 非常感谢!完全有道理,我相信关于类型转换的内容将来会派上用场
【解决方案2】:

其他人提到使用= vs == vs === - 这绝对是您的问题,但您在比较样式时也会遇到其他问题。

style 属性独特且繁琐。您拥有“样式”属性,它是 DOM 节点的属性(就像 href 用于锚点或 type 用于输入)。然后你就有了从样式表应用的样式——&lt;style&gt; 标签或外部样式表文件。有时两种不同的样式来源会发生冲突。

对于样式属性,您可以像现在一样阅读node.style.color 属性。要获得应用于节点的实际颜色,您必须使用window.getComputedStyle()。让我通过例子来解释一下区别:

const div = document.getElementById('foo')
div.style.color; //-> red
window.getComputedStyle(div).color; //-> rbg(0, 255, 0)
#foo { color: green !important }
&lt;div id="foo" style="color: red"&gt;Hello!&lt;/div&gt;

请注意我们如何在节点本身上设置red,但在样式表中设置green !important!important 将获胜,这就是文本为绿色的原因。此外,浏览器将颜色名称 green 转换为其 RGB 等效名称 rgb(0, 255, 0)。协调起来可能很乏味。我通常建议使用多个类名并在点击时在这些类名之间切换:

var header = document.getElementById("header");
var button = document.getElementById("button");

button.addEventListener("click", function() {
  if (header.classList.contains("red")) {
    header.classList.remove("red")
    header.classList.add("blue")
  } else if (header.classList.contains("blue")) {
    header.classList.remove("blue")
    header.classList.add("red")
  }
})
.red { color: red }
.blue { color: blue }
<h1 id="header" class="red"> Here's some text </h1>
<button id="button"> Change the Color </button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 2020-07-23
    • 2015-09-07
    • 2016-11-10
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多