为什么addEventListener不适合这个项目?

时间:2016-09-27 23:22:03

标签: javascript addeventlistener



document.getElementById('btn').addEventListener("onclick", mouseover);

function mouseover() {
  this.style.color = " yellow ";
  this.style.backgroundcolor = "green";
}

<input type="button" value= "Submit" id="btn" />
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

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

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

没有&#34; on&#34;在第二种方法中的事件名称之前,所以在您的情况下,您的代码应该是:

&#13;
&#13;
var btn = document.getElementById('btn');
btn.addEventListener("click", mouseover);
                   // ^-- note no "on" here

function mouseover() {
  this.style.color = "yellow";
  this.style.backgroundColor = "green";
}
&#13;
<input type="button" value= "Submit" id="btn" />
&#13;
&#13;
&#13;

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

答案 1 :(得分:1)

你有一些问题,评论解释了什么是错误的。

&#13;
&#13;
//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
&#13;
<button id="a" type="button">a</button>
&#13;
&#13;
&#13;

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

&#13;
&#13;
function makeActive() { 
  this.classList.toggle("active")
}

var btn = document.getElementById("a");
btn.addEventListener("click", makeActive);  
&#13;
button {
  background-color: #CCC;
}

.active {
   color: yellow;
   background-color: green;
}
&#13;
<button id="a" type="button">a</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试仅使用click代替onclick

btn.addEventListener("click", mouseover);

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

上述评论也是正确的,以便从Javascript使用style.backgroundColor

引用背景颜色