Home > Article > Web Front-end > Understanding events in js
1. What is a JavaScript event?
Events are specific moments of interaction that occur in a document or browser.
2. Event flow
Event flow describes the sequence of receiving events from the page, including the event bubbling flow proposed by IE and the event capture flow proposed by Netscape. The browser default is event bubbling flow.
Two ideas:
The event flow of IE is called event bubbling, that is, the event is initially accepted by the most specific element, and then propagates upward to less specific nodes step by step.
Another event stream proposed by the Netscape team is called event capture. The idea of event capture is that less specific DOM nodes should receive events earlier, while the most specific nodes should receive events last.
3. Event handler
There are several ways to specify a handler for an event. HTML event handler. That is, we add the event handler directly in the HTML code,
eg:
<script></p>
<p> function showmsg(){</p>
<p> alert("HTML add event handling"); /script></p>
<p> We can see from the above code 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 I If I want to change showmsg in js, then I not only need to modify it in js, I also need to modify it in html. </p>
<p> (1)DOM0 level event handler</p> That is to add event processing for the specified object, such as: <p> <input id="btn2" value="Button" type="button"> </p> <script><p> var btn2= document.getElementById("btn2");<br> btn2.onclick=function(){<br> alert("DOM0 level added event processing");<br> } <br> btn.onclick=null;//If you want to delete the click event of btn2, just set it to null<br> </script>
(2)DOM2-level event handler DOM2-level events define two methods for handling the operations of specifying and removing event handlers: addEventListener() and removeEventListener(). These two methods are included in all DOM nodes, and they both accept 3 parameters: the name of the event to be processed, the function as the event handler and a Boolean value. If the last parameter is true, it means that the event handler is called in the capture phase; if it is fasle, it means that the event handler is called in the bubbling phase.
The above is the detailed content of Understanding events in js. For more information, please follow other related articles on the PHP Chinese website!