为什么不是't为该项目工作的addEventListener

Why isn't addEventListener working for this project?

本文关键字:项目 工作 addEventListener 为什么不      更新时间:2023-09-26

document.getElementById('btn').addEventListener("onclick", mouseover);
function mouseover() {
  this.style.color = " yellow ";
  this.style.backgroundcolor = "green";
}
<input type="button" value= "Submit" id="btn" />

要将侦听器连接到名为的事件,请单击,您需要执行以下操作之一:

object.onclick = function(event) { ... }
object.addEventListener('click', function(event) { ... });

在第二种方法中,事件名称之前没有"on">,因此在您的情况下,您的代码应该是:

var btn = document.getElementById('btn');
btn.addEventListener("click", mouseover);
                   // ^-- note no "on" here
function mouseover() {
  this.style.color = "yellow";
  this.style.backgroundColor = "green";
}
<input type="button" value= "Submit" id="btn" />

(还要注意,它是backgroundColor,而不是background.color,并且颜色字符串中不应该有空格。(

您有一些问题,注释解释了问题所在。

//define the function first (best practice)
function mouseovera() { 
  this.style.color = "yellow";  //remove the spaces
  this.style.backgroundColor = "green"; //It is camel case not dot
}
var btn = document.getElementById("a");
btn.addEventListener("click", mouseovera);  //it is click, not onclick
<button id="a" type="button">a</button>

现在,更好的方法是使用类。使用classList,您可以在单击按钮时轻松切换类或添加类。当您使用一个类时,很容易在JavaScript代码之外维护它们的样式。

function makeActive() { 
  this.classList.toggle("active")
}
var btn = document.getElementById("a");
btn.addEventListener("click", makeActive);  
button {
  background-color: #CCC;
}
.active {
   color: yellow;
   background-color: green;
}
<button id="a" type="button">a</button>

试着只使用click而不是onclick

btn.addEventListener("click", mouseover);
function mouseover() {
  this.style.color = " yellow ";
  this.style.backgroundColor = "green";        
}

此外,上面的评论是正确的,即要引用Javascript中的背景颜色,请使用style.backgroundColor