如何處理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.pswp.cn/news/393917.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393917.shtml
英文地址,請注明出處:http://en.pswp.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…