In this blog, I will try to make clear the fundamentals of the event handling mechanism in JavaScript, without the help of any external library like Jquery/React/Vue.

在此博客中,我将尝试在没有任何外部库(例如Jquery / React / Vue)的帮助下阐明JavaScript中事件处理机制的基础。

I will be explaining the following topics in this article:

我将在本文中解释以下主题:

  1. The document and window objects, and adding Event Listeners to them.

    文档窗口对象,并向其中添加事件监听器

  2. The Event.preventDefault() method and it’s usage.

    Event.preventDefault()方法及其用法。

  3. The Event.stopPropagation() method with an example.

    带示例的Event.stopPropagation()方法。

  4. How to remove an event listener from an element.

    如何从元素中删除事件侦听器。

具有事件监听器的 文档窗口对象 (Document and window objects with Event Listeners)

The Window object represents the tab. In case you are reading this blog on your corresponding browser, then your current tab represents the Window object.

Window对象代表选项卡。 如果您正在相应的浏览器上阅读此博客,则当前的选项卡表示Window对象。

The window object has access to such information as the toolbar, height and width of the window, prompts, and alerts. Let’s see how we can add an event listener (mousedown) to the window object and analyze some of its properties.

窗口对象可以访问诸如工具栏,窗口的高度和宽度,提示和警报之类的信息。 让我们看看如何向窗口对象添加事件监听器(mousedown)并分析其某些属性。

如何在窗口对象上添加侦听器 (How to add the listener on the window object)

The addEventListener method is the most preferred way to add an event listener to window, document or any other element in the DOM.

addEventListener方法是将事件侦听器添加到window文档或DOM中任何其他元素的最优选方法。

There is one more way called “on” property onclick, onmouseover, and so on. But is not as useful, as it does not allow us to add multiple event listeners on the same element. The other methods allow it.

还有另一种称为“ on”属性的方法,例如onclick,onmouseover等。 但是它没有用,因为它不允许我们在同一元素上添加多个事件侦听器。 其他方法允许它。

An event object is passed as an argument (optional) to the handler which contains all the information related to the event (in our case, mousedown) on the window.

事件对象作为参数(可选)传递给处理程序,该处理程序包含窗口上与事件相关的所有信息(在我们的情况下为mousedown)。

Open the developer tools (Inspect Element) on this page and copy paste the following code in the console panel and hit enter.

打开此页面上的开发人员工具(检查元素),然后将以下代码复制粘贴到控制台面板中,然后按Enter。

window.addEventListener("mousedown",function(event){alert("window");console.log(event);
});

After that, you can go over to any section of the current tab and right click to see the console and the info related to this event, as shown below in the snapshot.

之后,您可以转到当前选项卡的任何部分,然后右键单击以查看控制台和与此事件相关的信息,如下快照所示。

Note: If you go to any other tab and right click, then this event will not get fired as it belongs to this tab (Window object) only.

注意 :如果转到任何其他选项卡并单击鼠标右键,则不会触发此事件,因为该事件仅属于此选项卡(Window对象)。

mousedown事件的详细信息 (The details of the mousedown event)

In the next few lines, I will explain some of the important captured property corresponding to the mousedown event we just performed.

在接下来的几行中,我将解释一些与我们刚刚执行的mousedown事件相对应的重要捕获属性。

button: As this was the mousedown event, it will tell you the button you clicked. For the mouse, Left, middle, and right correspond to 0, 1, and 2 respectively. If you click the right button, you can see the value 2.

button :由于这是mousedown事件,它将告诉您单击的按钮。 对于鼠标,左,中和右分别对应于0、1和2。 如果单击右键,则可以看到值2。

clientX and clientY: Position relative to the upper left of the content area (Viewport). Just analyze the value of these properties with the place you clicked, and you can see how they’re related. Even if you scroll down the page, these properties remain the same. ScreenX and ScreenY reference from the top left of the screen (Monitor).

clientXclientY :相对于内容区域(视口)左上方的位置。 只需单击您的位置来分析这些属性的值,就可以看到它们之间的关系。 即使向下滚动页面,这些属性也保持不变。 屏幕左上方(监视)的ScreenX和ScreenY参考。

altkey / ctrlkey: If you keep any of these keys pressed while performing your right click operation, then you can see these values are true. Otherwise, they’re false as in our case.

altkey / ctrlkey :如果在执行右键单击操作时按住这些键中的任何一个,则可以看到这些值是正确的。 否则,它们与我们的情况一样是错误的。

target: It corresponds to the element you performed the action upon. Whatever element you might have clicked on, you can see the information corresponding to this property in the console

目标:它对应于您对其执行操作的元素。 无论您单击什么元素,都可以在控制台中看到与此属性对应的信息

什么是文档对象 ? (What is a document object?)

The document consists of what is inside the inner window. The document object is the root of every node in the DOM. If you are loading an HTML page in the browser, then the document represents that entire page.

该文档由内部窗口中的内容组成。 文档 对象是DOM中每个节点的根。 如果要在浏览器中加载HTML页面,则文档代表整个页面。

Event.preventDefault()方法及其用法 (The Event.preventDefault() method and its usage)

Sometime we don’t want an HTML element to behave in the way it is supposed to behave in default. In such a case, we can use this method.

有时候,我们不希望HTML元素的行为与默认情况下的行为相同。 在这种情况下,我们可以使用这种方法。

Example: Clicking the anchor element will make the browser redirect to that page by default. Let’s try to avoid that.

示例 :单击锚点元素将使浏览器默认情况下重定向到该页面。 让我们尝试避免这种情况。

<html><body><a href="https://google.com/">Google</a><script>let link = document.querySelector("a"); // It is the method to access the first matched elementlink.addEventListener("click", function(event) {console.log("Redirecting Stopped");event.preventDefault();});</script>
</body></html>

You can create an HTML file and check out this code.

您可以创建一个HTML文件并签出此代码。

Event.stopPropagation()方法 (The Event.stopPropagation() method)

Events flow outwards. There are certain cases, such as when you have nested elements and you perform some event on a child and it ends up performing some action on the parent, too, that you want to avoid. In such cases, this method is a useful one.

事件向外流动。 在某些情况下,例如,当您具有嵌套元素并在子级上执行某些事件而最终在父级上执行某些操作时,也要避免这种情况。 在这种情况下,此方法是一种有用的方法。

It sounds bit confusing, but I hope the below example will make it clear to you.

这听起来有点令人困惑,但是我希望下面的例子能使您清楚。

Imagine you have a button inside a paragraph and you have attached a mousedown event to both of them. You want to achieve the following use cases:

想象一下,您在一个段落中有一个按钮,并且对它们两个都附加了mousedown事件。 您想要实现以下用例:

  1. If you right click the button, then it should show that it has been clicked and does not propagate to the parent element (that is, the paragraph).如果右键单击该按钮,则它应表明它已被单击,并且不会传播到父元素(即该段落)。
  2. If you left click on the button, then it should propagate outwards normally and fire the paragraph event listener, too.如果左键单击该按钮,则它应正常向外传播并触发段落事件侦听器。

Solution:

解:

<html><body><p id="demo"> Hello Ho<button id="button12"> Button2 </button> </p><script>// Event Listener on the Button and it's logicdocument.getElementById("button12").addEventListener("mousedown", function(event) {alert("button clicked");if (event.button == 2) // Right Clickevent.stopPropagation();});// Event Listener on the paragraph element with it's logic:document.getElementById("demo").addEventListener("mousedown", function(event) {alert("Paragraph clicked");});</script>
</body></html>

从元素中删除 事件监听器 (Removing an event listener from an element)

In order to remove an event listener from an element, we need to call the removeEventListener method with the event name and the function name.

为了从元素中删除事件侦听器,我们需要使用事件名称和函数名称调用removeEventListener方法。

Note: when anonymous functions are passed, they don’t have memory mapping. So we need to define those functions outside the callback and then reference them here in the removeEventListener callback.

注意 :传递匿名函数时,它们没有内存映射。 因此,我们需要在回调之外定义这些函数,然后在removeEventListener回调中在此处引用它们。

Document.getElementbyId("id_name").removeEventListener("click",fn_name)

If you have reached this point, you should have a decent understanding of how Event Listeners work in the JavaScript.

如果您已经达到了这一点,那么您应该对事件监听器在JavaScript中的工作方式有一个不错的了解。

If, while working with your favorite library/Frameworks, you ever get stuck in the Events Handling part, then these basics should help you to resolve the issue.

如果在使用您喜欢的库/ Framework时遇到“事件处理”部分的困扰,那么这些基础知识应该可以帮助您解决问题。

翻译自: https://www.freecodecamp.org/news/event-handling-in-javascript-with-examples-f6bc1e2fff57/

如何处理JavaScript中的事件处理(示例和全部)相关推荐

  1. 【转】理解JavaScript中的事件处理

    这篇文章对于了解Javascript的事件处理机制非常好,将它全文转载于此,以备不时之需. 转载地址:http://www.cnblogs.com/binyong/articles/1750263.h ...

  2. [基础]Javascript中的继承示例代码

    面向对象的语言必须具备四个基本特征: 1.封装能力(即允许将基本数据类型的变量或函数放到一个类里,形成类的成员或方法) 2.聚合能力(即允许类里面再包含类,这样可以应付足够复杂的设计) 3.支持继承( ...

  3. 如何处理javascript中var类型有效数据极限值问题(超大数据)

    最近在做web项目中遇到一个从来未遇到的问题,这个问题相信做为web开发的程序员来说遇到的可能性比较小!那么这个问题是怎么样出现的呢?我们有该如何解决这个问题呢? 由于javascript是弱类型语言 ...

  4. javascript中的事件处理

    IE中为attachEvent,dettachEvent firefox中为标准addEventListener,removeEventListener

  5. 理解JavaScript中的事件

    在很多语言的学习中,"事件"都是一个比较难理解,但是又是一个很重要的概念.JavaScript中的事件处理也是一样,正因为有了事件处理,才会出现Ajax拖动的效果.本文就讨论一下J ...

  6. 如何在JavaScript中验证电子邮件地址

    如何在JavaScript中验证电子邮件地址? #1楼 与squirtle相比 ,这是一个复杂的解决方案,但是在正确验证电子邮件方面做得非常出色: function isEmail(email) { ...

  7. JavaScript 事件模型 事件处理机制

    这篇文章对于了解Javascript的事件处理机制非常好,将它全文转载于此,以备不时之需. 什么是事件? 事件(Event)是JavaScript应用跳动的心脏 ,也是把所有东西粘在一起的胶水.当我们 ...

  8. html数组显示,javascript中怎么输出数组?

    作为一个程序员对于数组遍历大家都不是很陌生,在开发中我们也经常要处理数组.下面我们来看一下JavaScript如何输出数组. JavaScript中可以通过循环遍历数组,在循环中使用document. ...

  9. JavaScript中的交互式网页/事件处理

    Programming languages like C, C++ etc are all based on synchronous coding approach i.e. the executio ...

最新文章

  1. Python循环中的变量作用域的灵异现象
  2. 万恶之源:C语言中的隐式函数声明
  3. 《搬砖日记》Obi Rope插件的简单使用
  4. 001_日志系统的架构模型
  5. LYNC显示用户位置的相关配置
  6. 本科计算机论文摘要怎么写,★本科计算机论文摘要范文本科计算机论文摘要写...
  7. Git与GitHub的使用
  8. 每周论文清单:知识图谱,文本匹配,图像翻译,视频对象分割
  9. 【bzoj2006】【NOI2015】超级钢琴
  10. poj3463 最短路和次短路 计数
  11. 恢复系统管理员密码的五大奇招
  12. NTC热敏电阻温度计算方法,Steinhart-Hart方程和B值法
  13. 火山PC浏览文件和选择文件-通用对话框教程
  14. JQuery读书笔记---很全面的教程
  15. 第十一周项目2--定义点类
  16. 3维线程格 gpu_GPU的线程模型和内存模型
  17. go加密算法:非对称加密(三)--Elliptic
  18. Adobe Acrobat Pro DC 2022:专业高效的PDF阅读和编辑利器!
  19. 计算机体系结构:不同改进方案的性价比计算(1.4)
  20. 帮我写一份演化博弈的MATLAB代码

热门文章

  1. 万字总结!springcloud分布式限流
  2. 该如何高效实用Kotlin?看这一篇就够了!
  3. js包装类型的装箱拆箱
  4. 如何修改浏览器的默认滚动条样式
  5. hdu_2048 错排问题
  6. 【LeetCode】19. Remove Nth Node From End of List
  7. 遇到attemp to invoke virtual method
  8. RavenDB:基于Windows/.NET平台的NoSQL数据库
  9. C# 装箱和拆箱、理论概念(非原创)
  10. docker 启动的 jenkins 中调用宿主机docker进行build