警报(“嗨!”)和功能(){警报(“嗨!”)}之间的区别 [英] difference between alert("Hi!") and function(){alert("Hi!")}

查看:165
本文介绍了警报(“嗨!”)和功能(){警报(“嗨!”)}之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在按钮中执行内联命令时:

When we are doing inline command in the button:

<button id="myButton" onclick="alert('Hi!')"> 

为什么

document.getElementById("myButton").onclick = alert('Hi!') 

不起作用,但在页面加载时发出警报?我无法理解如何将 function()添加到它并且没有 function()。我希望你们理解我的问题。我在这里遗漏了一些东西。

not work but give the alert as the page is loaded? I can't understand how it works with function() added to it and without function(). I hope you guys understand my question. I'm missing something here.

推荐答案

document.getElementById("myButton").onclick = alert('Hi!')

错误,因为onclick应分配给函数引用,不是函数调用结果本身。

is wrong since onclick should be assigned to a function reference, not the function call result itself.

当页面加载时会执行 alert('嗨!')但这不是这里的意图, 是吗?分配onclick处理程序的目的是确保在单击按钮时将执行此警报。

It will execute alert('Hi!') when the page is loaded but that is not the intention here, is it? The intention behind assigning an onclick handler is to ensure that when the button is clicked this alert will be executed.

为此,它应该是:

document.getElementById("myButton").onclick = function(){alert('Hi!')};

此外,除非将其包含在 window.onload中,否则无法使用事件:

Also, this will not work unless it is wrapped inside the window.onload event:

window.onload = function(){
    document.getElementById("myButton").onclick = function(){alert('Hi!')};
};

这篇关于警报(“嗨!”)和功能(){警报(“嗨!”)}之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆