ホームページ ウェブフロントエンド jsチュートリアル JavaScriptイベントハンドリングメソッド(3種類)_JavaScriptスキル

JavaScriptイベントハンドリングメソッド(3種類)_JavaScriptスキル

May 16, 2016 pm 03:03 PM

Recently, because I have to modify the website every day and do special effects for the website, I have seen a lot of js exposure events. I only use a small part of it. Sometimes it is confusing when I use it. Now I have sorted it out systematically. Hereby share it on the Script House platform for your reference!

1. What is a JavaScript event?

Events are the beating heart of JavaScript applications and the glue that holds everything together. Events occur when we perform certain types of interactions with web pages in the browser.

The event may be the user clicking on some content, the mouse passing over a specific element or pressing certain keys on the keyboard. The event may also be something happening in the web browser, such as a web page loading. Done, or the user scrolls or resizes the window. To put it bluntly, an event is a specific moment of interaction that occurs in a document or browser!

By using JavaScript, you can listen for specific events to occur and specify that certain events occur in response to those events.

2. Event flow

Event flow describes the order in which events are received on a page. In the early days of browser development, the two major browser manufacturers IE and Netscape were competing with each other, and a pitfall occurred, that is, their interpretation of event flow emerged. Two completely opposite definitions. That is what we are familiar with: IE's event bubbling, Netscape's event capture. Let’s take a picture first to briefly look at the structure:

1. Event bubbling

Event bubbling means that the event is initially received by the most specific element (the node with the deepest nesting level in the document), and then propagates upwards to the least specific node (document). Take the above picture to illustrate, when the text part is clicked, it is first received by the element at the text, and then propagated to the window step by step, that is, the process of 6-7-8-9-10 is executed.

2. Event capture

Event capture means that the event is received by the less specific node first, and the most specific node receives the event last. Similarly, in the above model, when the text part is clicked, it is first received by the window and then propagated to the text element step by step, that is, the process of 1-2-3-4-5 is executed.

How is it expressed in the code? Will be given later!

3. Three ways of Javascript event handlers

When an event occurs, we have to handle it. There are three main methods of Javascript event handlers:

1. HTML event handler

That is, we add the event handler directly in the HTML code, such as the following code:

<input id="btn" value="按钮" type="button" onclick="showmsg();">
  <script>
   function showmsg(){
   alert("HTML添加事件处理");
   }
  </script> 
ログイン後にコピー

From the above code, we can see that event processing is directly nested in the element. This has a problem: the coupling between html code and js is too strong. If one day you want to change showmsg in js, Then not only do you need to modify it in js, but you also need to modify it in html. We can accept one or two modifications, but when your code reaches the level of 10,000 lines, modification will require a lot of time and money, so we do not use this method. Recommended.

2. DOM level 0 event handler

That is to add event processing for the specified object, look at the following piece of code:

<input id="btn" value="按钮" type="button">
  <script>
    var btn= document.getElementById("btn");
   btn.onclick=function(){
      alert("DOM级添加事件处理");
    } 
    btn.onclick=null;//如果想要删除btn的点击事件,将其置为null即可
  </script> 
ログイン後にコピー

From the above code, we can see that compared to HTML event handlers, DOM level 0 events, the coupling between html code and js code has been greatly reduced. However, smart programmers are still not satisfied and hope to find a simpler way to deal with it. Let's look at the third way to deal with it.

3. DOM2 level event handler

DOM2 also adds event handlers to specific objects, but mainly involves two methods for handling the operations of specifying and deleting event handlers: addEventListener() and removeEventListener(). They all receive three parameters: the event name to be processed, the function as the event handler and a Boolean value (whether to handle the event in the capture phase), look at the following piece of code:

<input id="btn" value="按钮" type="button">
  <script>
   var btn=document.getElementById("btn");
   btn.addEventListener("click",showmsg,false);//这里我们把最后一个值置为false,即不在捕获阶段处理,一般来说冒泡处
理在各浏览器中兼容性较好
   function showmsg(){
   alert("DOM级添加事件处理程序");
   }
   btn.removeEventListener("click",showmsg,false);//如果想要把这个事件删除,只需要传入同样的参数即可
  </script>
ログイン後にコピー

Here we can see that when adding and deleting event processing, the last method is more direct and simplest. However, Ma Haixiang reminds everyone that when processing the deletion event, the parameters passed in must be consistent with the previous parameters, otherwise the deletion will be invalid!

4. The process and difference between event bubbling and event capturing

Speaking of which, let me give you some code to explain the process of event bubbling and event capture, and also let you see the difference between the two:

<!doctype html>
  <html lang="en">
  <head>
   <meta charset="UTF-">
   <title>Document</title>
   <style>
   #p{width:px;height:px;border:px solid black;}
   #c{width:px;height:px;border:px solid red;}
   </style>
  </head>
  <body>
   <div id="p">
   i am www.mahaixiang.cn
   <div id="c">i like www.mahaixiang.cn</div>
   </div>
   <script>
   var p = document.getElementById('p');
     var c = document.getElementById('c');
   c.addEventListener('click', function () {
   alert('子节点捕获')
   }, true);
   c.addEventListener('click', function () {
   alert('子节点冒泡')
   }, false);
   p.addEventListener('click', function () {
   alert('父节点捕获')
   }, true);
   p.addEventListener('click', function () {
   alert('父节点冒泡')
   }, false);
   </script>
  </body>
</html> 
ログイン後にコピー

上記のコードを実行し、子要素をクリックすると、親ノードのキャプチャ - 子ノードのキャプチャ - 子ノードのバブリング - 親ノードのバブリングという順序で実行されることがわかります。この例から、DOM レベル 2 イベントには次の 3 つの段階が含まれることが規定されています。

1. イベントキャプチャフェーズ

2. ターゲットステージで

3. イベントバブリングステージ。

最初にキャプチャが行われ、次にターゲットの段階 (つまり、イベントが送信される場所に関して) が行われ、最後にバブリングが行われます。非科学的なのは、DOM1 レベルのイベント ハンドラーが存在しないことです。冗談は言わないでください。

5. 補足

1. IE イベント ハンドラーには、イベントを追加するためのattachEvent() とイベントを削除するための detachEvent() という 2 つのメソッドもあります。これらの 2 つのメソッドは、イベント ハンドラー名とイベント処理関数という同じ 2 つのパラメーターを受け取ります。ここにブール値がないのはなぜですか? IE8 以前のバージョンではイベント バブリングのみがサポートされているため、最後のパラメータのデフォルトは false です。 (IE イベント ハンドラーをサポートするブラウザには、IE と Opera が含まれます)。

2. イベント オブジェクトは、イベントの発生時に関連情報を記録するために使用されるオブジェクトですが、イベント オブジェクトはイベントの発生時にのみ生成され、すべてのイベント処理関数の後、イベント処理関数内でのみアクセスできます。の実行が終了すると、イベント オブジェクトが破棄されます。

以上、編集者が紹介したJavaScriptのイベント処理メソッド(3種類)です。ご参考になれば幸いです。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JavaScriptの文字列文字を交換します JavaScriptの文字列文字を交換します Mar 11, 2025 am 12:07 AM

JavaScript文字列置換法とFAQの詳細な説明 この記事では、javaScriptの文字列文字を置き換える2つの方法について説明します:内部JavaScriptコードとWebページの内部HTML。 JavaScriptコード内の文字列を交換します 最も直接的な方法は、置換()メソッドを使用することです。 str = str.replace( "find"、 "置換"); この方法は、最初の一致のみを置き換えます。すべての一致を置き換えるには、正規表現を使用して、グローバルフラグGを追加します。 str = str.replace(/fi

jQuery日付が有効かどうかを確認します jQuery日付が有効かどうかを確認します Mar 01, 2025 am 08:51 AM

単純なJavaScript関数は、日付が有効かどうかを確認するために使用されます。 関数isvaliddate(s){ var bits = s.split( '/'); var d = new Date(bits [2] '/' bits [1] '/'ビット[0]); return !!(d &&(d.getmonth()1)== bits [1] && d.getdate()== number(bits [0])); } //テスト var

jQueryは要素のパディング/マージンを取得します jQueryは要素のパディング/マージンを取得します Mar 01, 2025 am 08:53 AM

この記事では、jQueryを使用して、DOM要素の内側のマージン値とマージン値、特に外側の縁と要素の内側の縁の特定の位置を取得して設定する方法について説明します。 CSSを使用して要素の内側と外側の縁を設定することは可能ですが、正確な値を取得するのは難しい場合があります。 // 設定 $( "div.header")。css( "margin"、 "10px"); $( "div.header")。css( "padding"、 "10px"); このコードはそうだと思うかもしれません

10 jQuery Accordionsタブ 10 jQuery Accordionsタブ Mar 01, 2025 am 01:34 AM

この記事では、10個の例外的なjQueryタブとアコーディオンについて説明します。 タブとアコーディオンの重要な違いは、コンテンツパネルの表示方法と非表示にあります。これらの10の例を掘り下げましょう。 関連記事:10 jQueryタブプラグイン

10 jqueryプラグインをチェックする価値があります 10 jqueryプラグインをチェックする価値があります Mar 01, 2025 am 01:29 AM

ウェブサイトのダイナミズムと視覚的な魅力を高めるために、10の例外的なjQueryプラグインを発見してください!このキュレーションされたコレクションは、画像アニメーションからインタラクティブなギャラリーまで、多様な機能を提供します。これらの強力なツールを探りましょう。 関連投稿: 1

ノードとHTTPコンソールを使用したHTTPデバッグ ノードとHTTPコンソールを使用したHTTPデバッグ Mar 01, 2025 am 01:37 AM

HTTP-Consoleは、HTTPコマンドを実行するためのコマンドラインインターフェイスを提供するノードモジュールです。 Webサーバー、Web Servに対して作成されているかどうかに関係なく、HTTPリクエストで何が起こっているかをデバッグして正確に確認するのに最適です

カスタムGoogle検索APIセットアップチュートリアル カスタムGoogle検索APIセットアップチュートリアル Mar 04, 2025 am 01:06 AM

このチュートリアルでは、カスタムGoogle検索APIをブログまたはWebサイトに統合する方法を示し、標準のWordPressテーマ検索関数よりも洗練された検索エクスペリエンスを提供します。 驚くほど簡単です!検索をyに制限することができます

jQueryはscrollbarをdivに追加します jQueryはscrollbarをdivに追加します Mar 01, 2025 am 01:30 AM

次のjQueryコードスニペットを使用して、Divコンテンツがコンテナ要素領域を超えたときにスクロールバーを追加できます。 (デモンストレーションはありません、それを直接firebugにコピーしてください) // d =ドキュメント // w =ウィンドウ // $ = jQuery var contentarea = $(this)、 wintop = contentarea.scrolltop()、 docheight = $(d).height()、 winheight = $(w).height()、 divheight = $( '#c

See all articles