[英]Assign Events Using the HTML DOM JS
I am learning JS,and I have an example which I don't understand. 我正在学习JS,我有一个我不理解的例子。 When we call functions like this it works:
当我们调用这样的函数时,它将起作用:
<button onclick="displayDate()">Try it</button>
This also works: 这也适用:
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
But when I change this displayDate
to displayDate()
it shows me the date when page is loaded,so onclick doesn't work. 但是,当我将此
displayDate
更改为displayDate()
它会显示页面加载的日期,因此onclick不起作用。 My question is: why does JS DOM work like this? 我的问题是:为什么JS DOM会这样工作? What is really happening?
到底发生了什么事? Do we not call a function like this:
function();
我们不调用这样的函数吗:
function();
? ?
When you write: 当你写:
something = functionName();
it means to call the function immediately, and then put the value that it returns into something
. 这意味着立即调用该函数,然后将其返回的值放入
something
。
When you write: 当你写:
something = functioName;
it means to put a reference to the function into something
, but not call it. 这意味着将对函数的引用放入
something
,但不调用它。 This allows the function to be called later, using that reference. 这样可以稍后使用该引用调用该函数。 When
something
is someElement.onclick
, this happens when the user clicks on the element. 当
something
为someElement.onclick
,这会在用户单击该元素时发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.