本文介绍了addeventlistener不起作用,事件不等待点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为网页执行Javascript练习,我想要的是在单击按钮时出现一行文本,问题是文本只是在单击按钮之前出现。我所有的标签和ID都是正确的。

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


推荐答案

问题是您尝试将事件监听器设置为调用 earthTime 函数的结果,并且实际上是未定义,因为您什么都不返回。

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

这篇关于addeventlistener不起作用,事件不等待点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:27