我的老师说javascript中的onclick是一个事件和一个事件处理程序。但是我不能同意她的看法,我发现它们是不同的,但是不能正确地区分。做了很多的谷歌搜索,找不到任何相关的东西。所以有人请区分事件和事件处理程序。
根据https://developer.mozilla.org上的文档。
事件:
发送事件以将发生的事情通知代码。每个事件都由一个基于事件接口的对象表示,并且可能具有其他自定义字段和/或用于获取有关发生的事件的其他信息的函数。事件可以代表一切,从基本的用户交互到网页中发生的事件的自动通知。
事件处理程序:
在事件触发时执行某些操作的函数或代码行称为事件处理程序。
例如:
click
是单击某些内容时触发的事件。
onclick
是事件处理程序,在单击事件发生时会执行某些操作。
<button onClick="alert('You clicked me');">Click me to fire a click event</button>
在上面的示例中,当按钮上发生单击事件时,事件处理程序(onClick)会执行警报和显示消息的工作。
事件处理程序也可以附加到某些事件,例如下面的示例:
document.getElementById('sampleParagraph').addEventListener("click", function(){
//I am the event handler Function
alert("A click event occured on the paragraph");
});
<p id="sampleParagraph">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum
</p>
在上面的示例中,我们在该事件上附加了事件处理程序,该事件在单击事件时向您显示警报。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句