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

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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393917.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

js 图片预览

//显示选择的图片缩略图function showImage(inputId,imageConfirmId,imageConfi){var imagedocument.getElementById(inputId).value.toLowerCase();if(!image){return;}var fileExtendimage.substr(image.lastIndexOf(".", image.length)1);if(!(fileExtend"jp…

什么是copyonwrite容器

2019独角兽企业重金招聘Python工程师标准>>> CopyOnWrite容器即写时复制的容器。通俗的理解是当往一个容器添加元素的时候&#xff0c;不直接往当前容器添加&#xff0c;而是先将当前容器进行Copy&#xff0c;复制出一个新的容器&#xff0c;然后新的容器里添加元素…

hystrix 源码 线程池隔离_Hystrix源码学习--线程池隔离

分析你的系统你所认识的分布式系统&#xff0c;哪些是可以进行垂直拆分的&#xff1f;拆分之后系统之间的依赖如何梳理&#xff1f;系统异构之后的稳定性调用如何保证&#xff1f;这些都是可能在分布式场景中面临的问题。说个比较常见的问题&#xff0c;大家都知道秒杀系统&…

P2341 [HAOI2006]受欢迎的牛 强连通

题目背景 本题测试数据已修复。 题目描述 每头奶牛都梦想成为牛棚里的明星。被所有奶牛喜欢的奶牛就是一头明星奶牛。所有奶 牛都是自恋狂&#xff0c;每头奶牛总是喜欢自己的。奶牛之间的“喜欢”是可以传递的——如果A喜 欢B&#xff0c;B喜欢C&#xff0c;那么A也喜欢C。牛栏…

oracle em agent,ORACLE 11G EM 配置命令及问题处理

11g装好以后&#xff0c;一直未用EM,昨天晚上和今天晚上终于抽时间把EM启动起来了&#xff0c;还遇到一点小问题&#xff0c;1.EM配置的一些命令创建一个EM资料库emca -repos create重建一个EM资料库emca -reposrecreate--------这个很主要&#xff0c;一般第一次不成功创建的时…

leetcode89. 格雷编码

格雷编码是一个二进制数字系统&#xff0c;在该系统中&#xff0c;两个连续的数值仅有一个位数的差异。 给定一个代表编码总位数的非负整数 n&#xff0c;打印其格雷编码序列。即使有多个不同答案&#xff0c;你也只需要返回其中一种。 格雷编码序列必须以 0 开头。 示例 1:…

注重代码效率_如何提升质量:注重态度

注重代码效率by Harshdeep S Jawanda通过Harshdeep S Jawanda 如何提升质量&#xff1a;注重态度 (How to skyrocket quality: focus on attitude) When it comes to discussing quality and how we can improve, the most common things that come to peoples minds are test…

spark mllib推荐算法使用

2019独角兽企业重金招聘Python工程师标准>>> 一、pom.xml <!-- 机器学习包 --><dependency><groupId>org.apache.spark</groupId><artifactId>spark-mllib_2.10</artifactId><version>${spark.version}</version>&…

Android仿QQ复制昵称效果2

本文同步自http://javaexception.com/archives/77 背景: 在上一篇文章中&#xff0c;给出了一种复制QQ效果的方案&#xff0c;今天就来讲讲换一种方式实现。主要依赖的是一个开源项目https://github.com/shangmingchao/PopupList。 解决办法: PopupList.java的代码封装的比较完…

R语言的自定义函数—字符组合

前两天写了几个函数&#xff0c;对里面收获到的一些东西做一些记录。 函数str_comb&#xff0c;用于输入一个字符串或数值向量&#xff0c;返回由向量中元素组成的不重复的长度小于向量长度的所有组合&#xff0c;结果用矩阵形式输出。 函数使用结果如下&#xff1a; 思路很简单…

oracle group by 两项,Oracle中group by 的扩展函数rollup、cube、grouping sets

Oracle的group by除了基本使用方法以外&#xff0c;还有3种扩展使用方法&#xff0c;各自是rollup、cube、grouping sets。分别介绍例如以下&#xff1a;1、rollup对数据库表emp。如果当中两个字段名为a&#xff0c;b,c。假设使用group by rollup(a,b)&#xff0c;首先会对(a,b…

leetcode1079. 活字印刷(回溯)

你有一套活字字模 tiles&#xff0c;其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。 注意&#xff1a;本题中&#xff0c;每个活字字模只能使用一次。 示例 1&#xff1a; 输入&#xff1a;“AAB” 输出&#xff1a;8 解释&#xff1a;可能的…

什么从什么写短句_从什么到从什么造句

从什么到从什么造句从什么到从什么怎么来造句呢?以下是小编为大家收集整理的从什么到从什么造句&#xff0c;希望对你有所帮助&#xff01;从什么到从什么造句&#xff1a;从闻到花香到看到花朵,从看到花朵到触摸到花瓣,真是一种美妙的感觉.从今天到明天&#xff0c;从明天到后…

如何开发一个hexo主题_如何确定一个强烈的主题可以使产品开发更有效

如何开发一个hexo主题by Cameron Jenkinson卡梅伦詹金森(Cameron Jenkinson) 如何确定一个强烈的主题可以使产品开发更有效 (How identifying a strong theme can make product development more effective) MVPs always seem easy to execute and build. The first version i…

机器学习基石13-Hazard of Overfitting

注&#xff1a; 文章中所有的图片均来自台湾大学林轩田《机器学习基石》课程。 笔记原作者&#xff1a;红色石头 微信公众号&#xff1a;AI有道 上节课主要介绍了非线性分类模型&#xff0c;通过非线性变换&#xff0c;将非线性模型映射到另一个空间&#xff0c;转换为线性模型…

容器为何物,为什么它对OpenStack很重要?

本文讲的是容器为何物&#xff0c;为什么它对OpenStack很重要&#xff0c;【编者的话】本文主要介绍了容器的发展、容器技术、容器类型、Docker、Open Container Initiative、微服务以及OpenStack中容器的应用。 容器现在正经历着一次重生&#xff0c;部分原因是由于云计算的发…

oracle执行计划的rows不对,Oracle执行计划——all_rows和first_rows(n)优化器模式

Oracle执行计划——all_rows和first_rows(n)优化器模式0. 环境创建[sql]SQL> create usertest identified by test2 default tablespace users3 temporary tablespace temp4 quota unlimited on users;User created.SQL> grant createsession, resource, alter session t…

从 MVC 到前后端分离

转载自&#xff1a;https://my.oschina.net/huangyong/blog/521891 从MVC到前后端分离 1.理解 MVC MVC是一种经典的设计模式&#xff0c;全名为Model-View-Controller&#xff0c;即模型-视图-控制器。其中&#xff0c;模型是用于封装数据的载体&#xff0c;例如&#xff0c;在…

leetcode93. 复原IP地址(回溯)

给定一个只包含数字的字符串&#xff0c;复原它并返回所有可能的 IP 地址格式。 有效的 IP 地址正好由四个整数&#xff08;每个整数位于 0 到 255 之间组成&#xff09;&#xff0c;整数之间用 ‘.’ 分隔。 示例: 输入: “25525511135” 输出: [“255.255.11.135”, “255…

vj节点_创意编码—如何在JavaScript中创建VJ引擎

vj节点by George Gally通过乔治加利 创意编码—如何在JavaScript中创建VJ引擎 (Creative Coding — How to create a VJ engine in JavaScript) 了解如何将JavaScript动态注入网页 (Learn how to dynamically inject JavaScript into webpages) For years I’ve been using th…