ホームページ >ウェブフロントエンド >jsチュートリアル >JavaScriptイベントハンドリングメソッド(3種類)_JavaScriptスキル
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種類)です。ご参考になれば幸いです。