addeventlistener not working, event not waiting for on click

感情迁移 提交于 2020-04-07 09:34:09

问题


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. All my tags and ids are correct.

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;}

回答1:


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.

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;
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/54384420/addeventlistener-not-working-event-not-waiting-for-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!