简体   繁体   English

addeventlistener 不工作,事件不等待点击

[英]addeventlistener not working, event not waiting for on click

I am working on a Javascript exercise for a web page and what I want is for a line of text to appear when I click on a button, problem is that the text just appears before I click on the button.我正在为 web 页面进行 Javascript 练习,我想要的是当我单击按钮时出现一行文本,问题是文本只是在我单击按钮之前出现。 All my tags and ids are correct.我所有的标签和 ID 都是正确的。

document.getElementById("earth_time").setAttribute("hidden", true);
ocument.getElementById("earth_time_check").addEventListener("onclick", earthTime());
function earthTime(){
document.getElementById("earth_time").innerHTML = Date();
document.getElementById("earth_time").hidden = false;}

Your code looks fine to me, unless you may have made a typographical error on your second line of code. 您的代码对我来说看起来不错,除非您在第二行代码中犯了印刷错误。

document.getElementById("earth_time").setAttribute("hidden", true);
document.getElementById("earth_time_check").addEventListener("onclick", 
earthTime);

// define function earthTime
function earthTime(){
document.getElementById("earth_time").innerHTML = Date();
document.getElementById("earth_time").hidden = false;
}

The problem is that you try to set event listener to a result of the invocation of earthTime function, and it is effectively undefined because you return nothing from it. 问题是您尝试将事件侦听器设置为earthTime函数调用的结果,并且实际上是undefined因为您没有从它返回任何内容。

The proper way to set event listener is: 设置事件侦听器的正确方法是:

document.getElementById("earth_time").setAttribute("hidden", true);
// earthTime is without calling brackets
document.getElementById("earth_time_check").addEventListener("onclick", earthTime);

function earthTime(){
  document.getElementById("earth_time").innerHTML = Date();
  document.getElementById("earth_time").hidden = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM