In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
Today, the editor will share with you the relevant knowledge points of JavaScript event handling case analysis. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
one。 Event propagation mechanism
Client-side JavaScript programs (that is, browsers) use an asynchronous event-driven programming model. Web browsers generate event when something interesting happens to a document, browser, element, or related object. If the JavaScript application is concerned with specific types of events, it can register one or more functions to be called when such events occur. Of course, this style is not unique to Web programming, and is adopted by all applications that use a graphical user interface.
Since we want to explain event handling in detail, let's start with a few basic concepts:
① event type (event type): a string that describes what type of event occurred. For example, "mousemove" indicates that the user moves the mouse, and "keydown" indicates that a key on the keyboard is pressed. The event type is just a string, sometimes called the event name (event name).
② event target (event target): an object that occurs or is associated with an event. Window, Document, and Element objects are the most common event targets. Of course, the XMLHttpRequest object in AJAX is also an event target
③ event handler (event handler): a function that handles or responds to events, also known as event listeners (event listener). Applications register their event handlers in Web browsers by specifying event types and event targets.
④ event object (event object): an object that is related to a particular event and contains details about that event. The event object is passed as an argument to the event handler (but in IE8 and previous versions, the global variable event is the event object). Event objects all have a type property that specifies the event type (event type) and a target attribute that specifies the event target (event target) (but in IE8 and previous versions, srcElement is used instead of target). Of course, different types of events also define other unique properties for their related event objects. For example, the related object of the mouse event contains the coordinates of the mouse pointer, while the related object of the keyboard event contains the details of the pressed key and auxiliary key.
These are the four basic concepts mentioned above. So the question arises-- if you click a child element b of an element an on a web page, should you first execute the event handler registered by the child element b or the event handler registered by the element a (assuming that both element an and its child element b have registered event handlers)? As a reader, have you ever thought about this question?
This problem involves the event propagation (event propagation) mechanism in browsers. I'm sure you've all heard of event bubbling (event bubble) and event capture (event capturing). Yes, they are the event propagation mechanisms in browsers. No picture, no truth, no matching picture? Then how to be rich:
After looking at the figure, I believe you have a general understanding of the event propagation mechanism in the browser: when an event occurs, it will be passed all the way down from the browser object Window to the element that triggered the event, which is the event capture process. However, it's not over, and the event is passed all the way up from this element to the Window object, which is the event bubbling process (but in IE8 and previous versions, the event model does not define a capture process, only a bubbling process).
So, with regard to the above question, it depends on whether the event handler registered for element an is in the capture process or in the bubbling process. So what exactly registers the event handler during the capture process and how does the event handler register during the bubbling process? Here are a few ways to register event handlers:
1. Set the HTML tag property to the event handler
The event handler attribute of the document element, whose name consists of "on" followed by the event name, such as onclick, onmouseover. Of course, this form can only register event handlers for DOM elements. Example:
Test # div1 {width: 300px; height: 300px; background: red; overflow:hidden;} # div2 {margin:50px auto; width: 200px; height: 200px; background: green; overflow:hidden;} # div3 {margin:50px auto; width: 100px; height: 100px; background: blue;} div1 div2 div3
Result (after mouse click on div3 area):
As can be seen from the results:
① is not case-sensitive in HTML, so the property names of event handlers can be uppercase, lowercase and mixed case, and the attribute value is the JavaScript code of the corresponding event handler.
If ② writes multiple onclick event handling attributes to the same element, the browser will only execute the code in * onclick, and the rest will be ignored.
③ is a form that registers event handlers during event bubbling
two。 Set the JavaScript object property to the event handler
You can register an event handler for an event target by setting its event handler properties. The event handler property name consists of "on" followed by the event name, for example: onclick, onmouseover. Example:
Test # div1 {width: 300px; height: 300px; background: red; overflow:hidden;} # div2 {margin:50px auto; width: 200px; height: 200px; background: green; overflow:hidden;} # div3 {margin:50px auto; width: 100px; height: 100px; background: blue;} div1 div2 div3 var div1 = document.getElementById ('div1') Var div2 = document.getElementById ('div2'); var div3 = document.getElementById (' div3'); div1.onclick = function () {console.log ('div1');}; div2.onclick = function () {console.log (' div2');}; div3.onclick = function () {console.log ('div3');}; div1.onclick = function () {console.log (' div11111');}; div1.onClick = function () {console.log ('DIV11111');}
Result (after mouse click on div3 area):
As can be seen from the results:
① because JavaScript is strictly case-sensitive, this form of subordinate sexual name can only be lowercase as required.
If ② writes multiple onclick event handling attributes to the same element object, the following will overwrite the previous one (ps: this is modifying the value of an object property, the value of the attribute is * determined)
③ also registers event handlers during event bubbling.
3.addEventListener ()
The first two methods appeared in the early days of Web, and many browsers have implemented them. The addEventListener () method is defined in the standard event model. Any object that can be the target of an event-- including Window objects, Document objects, all document elements, and so on-- defines a method called addEventListener (), which allows you to register an event handler for the event target. AddEventListener () accepts three arguments: * is the event type of the handler to be registered, whose value is a string, but does not include the prefix "on"; the second parameter refers to the function that should be called when an event of the specified type occurs; and the third parameter is a Boolean, which can be ignored (this parameter cannot be ignored on some older browsers), and the default value is false. In this case, the event handler is registered during event bubbling. When it is true, the event handler is registered during the event capture process. Example:
Test
# div1 {width: 300px; height: 300px; background: red; overflow:hidden;}
# div2 {margin:50px auto; width: 200px; height: 200px; background: green; overflow:hidden;}
# div3 {margin:50px auto; width: 100px; height: 100px; background: blue;}
Div1
Div2
Div3
Var div1 = document.getElementById ('div1')
Var div2 = document.getElementById ('div2')
Var div3 = document.getElementById ('div3')
Div1.addEventListener ('click', function () {console.log (' div1-bubble');}, false)
Div2.addEventListener ('click', function () {console.log (' div2-bubble');}, false)
Div3.addEventListener ('click', function () {console.log (' div3-bubble');}, false)
Div3.addEventListener ('click', function () {console.log (' div3-bubble222');}, false)
Div1.addEventListener ('click', function () {console.log (' div1-capturing');}, true)
Div2.addEventListener ('click', function () {console.log (' div2-capturing');}, true)
Div3.addEventListener ('click', function () {console.log (' div3-capturing');}, true)
Result (after mouse click on div3 area):
As can be seen from the results:
The third parameter of ① addEventListener () works as mentioned above.
② registers multiple events of the same type to the same object through the addEventListener () method. Ignoring or overwriting does not occur, but executes sequentially.
Relative to addEventListener () is the removeEventListener () method, which also has three parameters, the first two parameters naturally have the same meaning as addEventListener (), and the third parameter only needs to be consistent with the third parameter of the corresponding addEventListener (), which can also be omitted, and the default value is false. It represents the removal of an event handler from the object. Example:
Div1.addEventListener ('click', div1BubbleFun, false); div1.removeEventListener (' click', div1BubbleFun, false); function div1BubbleFun () {console.log ('div1-bubble');}
4.attachEvent ()
However, addEventListener () and removeEventListener () are not supported by IE8 and previous versions of browsers. Accordingly, IE defines similar methods attachEvent () and detachEvent (). Because IE8 and previous browsers do not support event capture, attachEvent () cannot register event handlers during capture, so attachEvent () and detachEvent () require only two parameters: the event type and the event handler. Moreover, its * * parameters use the event handler property name with the prefix "on". Example:
Var div1 = document.getElementById ('div1'); div1.attachEvent (' onclick', div1BubbleFun); function div1BubbleFun () {console.log ('div1-bubble');}
Accordingly, the delete event handler function uses detachEvent () from the object. For example:
Div1.detachEvent ('onclick', div1BubbleFun)
So far, we have talked about the event propagation mechanism in browsers and various ways to register event handlers. Let's talk about some problems when event handlers are called.
two。 Calls to event handlers
1. Parameters for event handlers: as mentioned earlier, event objects are usually passed to event handlers as parameters, but the global variable event in IE8 and previous versions of browsers is the event object. Therefore, we should pay attention to compatibility when writing related code. Instance (add a click event to the element on the page where id is div1, and output the event type and the clicked element itself in the console when clicking on the element):
Test # div1 {width: 300px; height: 300px; background: red; overflow: hidden;} div1 var div1 = document.getElementById ('div1'); if (div1.addEventListener) {div1.addEventListener (' click', div1Fun, false);} else if (div1.attachEvent) {div1.attachEvent ('onclick', div1Fun);} function div1Fun (event) {event = event | window.event; var target = event.target | | event.srcElement; console.log (event.type) Console.log (target);}
two。 The environment in which the event handler runs: for the environment in which the event handler runs, that is, the pointing of the calling context (this value) in the event handler, you can take a look at the following four examples.
Example 1:
Test
# div1 {width: 300px; height: 300px; background: red; overflow: hidden;}
Div1 var div1 = document.getElementById ('div1'); div1.onclick = function () {console.log (' div1.onclick:'); console.log (this);}
Result 2:
As can be seen from the results:
The this in the ① second method event handler also points to the element itself.
When there is a second method in ②, it overrides event handlers registered by * methods.
Example 3:
Test # div1 {width: 300px; height: 300px; background: red; overflow: hidden;} div1 var div1 = document.getElementById ('div1'); div1.onclick = function () {console.log (' div1.onclick:'); console.log (this);}; div1.attachEvent ('onclick', function () {console.log (' div1.attachEvent:'); console.log (this = window)
});
Result 4:
As can be seen from the results:
① fourth method this points to the global object Window in the event handler
The fourth method of ② does not overwrite event handlers registered by * or the second method.
3. The calling order of event handlers: the calling rules of multiple event handlers are as follows:
Handlers registered by ① through the HTML property and handlers that set object properties always have priority to call
Handlers registered by ② using addEventListener () are called in the order in which they are registered
Handlers registered by ③ with attachEvent () may be called in any order, so the code should not depend on the calling order
4. Event cancellation:
① cancels the browser default action for an event (for example, clicking on a hyperlink element automatically causes a page jump): if you register the event handler using the first two methods, you can add the return value false to the handler to cancel the browser default action for the event. In browsers that support addEventListener (), you can also cancel the default action for an event by calling the preventDefault () method of the event object. IE8 and its previous browsers can cancel the default action of the event by setting the returnValue property of the event object to false. Reference Code:
Function cancelHandler (event) {var event = event | | window.event; if (event.preventDefault) {event.preventDefault ();} if (event.returnValue) {event.returnValue = false;} return false;}
② cancels event propagation: in browsers that support addEventListener (), you can call a stopPropagation () method of the event object to prevent the event from continuing to propagate, which can work at any stage during the event propagation (capture phase, event target itself, bubbling phase). However, the stopPropagation () method is not supported in IE8 and previous browsers, and these browsers do not support the capture phase of event propagation. Accordingly, the IE event object has a cancelBubble property, which is set to true to prevent the event from propagating further (that is, preventing it from bubbling). Reference code (prevent click events that occur in the div3 area from bubbling to div2 and div1):
Test
# div1 {width: 300px; height: 300px; background: red; overflow:hidden;}
# div2 {margin:50px auto; width: 200px; height: 200px; background: green; overflow:hidden;}
# div3 {margin:50px auto; width: 100px; height: 100px; background: blue;}
Div1 div2 div3 var div1 = document.getElementById ('div1'); var div2 = document.getElementById (' div2'); var div3 = document.getElementById ('div3'); div1.onclick = function () {console.log (' div1');}; div2.onclick = function () {console.log ('div2');}; div3.onclick = function (event) {stopEventPropagation (event); console.log (' div3');}; function stopEventPropagation (event) {var event = event | | window.event If (event.stopPropagation) {event.stopPropagation ();} else {event.cancelBubble = true
}
}
These are all the contents of the article "JavaScript event handling case Analysis". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.