addeventlistener not working, event not waiting fo

2020-05-05 16:53发布

问题:

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