gpt4 book ai didi

javascript - 为什么 addEventListener 不适用于该项目?

转载 作者:行者123 更新时间:2023-11-28 18:22:04 26 4
gpt4 key购买 nike

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

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

最佳答案

要将监听器附加到名为 click 的事件,您需要执行以下操作之一:

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,并且颜色字符串中不应有空格。)

关于javascript - 为什么 addEventListener 不适用于该项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com