Js event listening mechanism (event capture) Summary, js listening

Source: Internet
Author: User

Js event listening mechanism (event capture) Summary, js listening

During front-end development, we often encounter the problem of adding events to page elements. There are also many js methods for adding events, which are directly added to the page structure, some js event listening methods are used. Because different browsers have different mechanisms for event bubbling event listening, le browser only has event bubbling and does not have event listening mechanisms, compatibility issues with event listening are the biggest problem:

1. directly write the event Method on the page Structure

Function eventfun () {// console. log (this) ;}< input type = "button" onclick = "eventfun ()" value = "button"/> // a question about this scope is involved, eventfun is a global function. The object is [object Window], and this points to window.

To solve the problem of this scope, you can use the method of adding event variables to the global function, and pass this object as a parameter to the function in the page structure.

<Input type = "button" onclick = "eventfun2 (this)" value = "button2"/> function eventfun2 (eve) {// here, the event object is passed as a parameter to the global method eve. name = "alex"; window. name = "robin"; console. log (this); // [object Window] console. log (eve); // [object HTMLInputElement] console. log (this. name); // robin console. log (eve. name); // alexvar self = eve; console. log (this. name); // robin console. log (self. name); // alex alert (window. name); alert (self. name );}

2. the method used to assign values to event properties is a method used to bind events. However, the limitation of this method is that only one method can be bound to the event. If multiple methods are bound, a later method prevails.

HTMLElementobject. onclick = fucntion () {// use this method to assign values to event properties. The pointer of this will point to the window object rather than the event object, so this method is referenced

// Js code fun1 (); fun2 (); fun3 (); console. log (this); // window. object} function dosomething () {// js code} HTMLElementobject. onclick = dosomething; // this method is used to assign values to the event object attribute. this Pointer Points to the event execution object console. log (this); // htmlElementObject

3. Event propagation-bubble and capture
The DOM Event standard defines two event streams, which are significantly different and may have a considerable impact on your application. The two event streams are capture and bubble. Like many Web technologies, Netscape and Microsoft implemented them differently before they became standards. Netscape selects to capture the event stream, while Microsoft implements the bubble event stream. Fortunately, W3C decided to combine these two methods, and most new browsers followed these two event stream methods.
By default, events use the bubble event stream instead of the capture event stream. However, in Firefox and Safari, You can explicitly specify to capture event streams by passing the useCapture parameter during event registration and setting this parameter to true.
Bubble event stream
When an event is triggered on a DOM element, for example, when you click the customer Name node, the event will follow the parent node inherited by the node to bubble through the entire DOM node hierarchy until it encounters a node attached to the Event-type processor, this event is an onclick event. You can terminate event bubbling at any time during the bubbling process. In a browser that complies with W3C standards, you can call the stopPropagation () method on the event object, in Internet Explorer, you can set the cancelBubble attribute of the event object to true. If you do not stop the event propagation, the event will always bubble through the DOM until it reaches the document root.
Capture event streams
Event Processing starts from the root of the DOM hierarchy, instead of starting from the target element of the trigger event. The event is passed down from all the ancestor elements of the target element. During this process, the event will be captured by each inherited element from the document root to the event Target element. If the event listener sets the useCapture attribute to true when it is registered, they can be assigned to any element during this period to handle the event; otherwise, the event will be passed to the next element on the derived element path until the target element. After the event arrives at the target element, it then bubbles through the DOM node.
Modern event binding method
As discussed in the previous lesson, binding with traditional events has many drawbacks. For example, you cannot register multiple event handler functions on the same event of an object. Browsers and W3C do not take this into consideration. Therefore, in modern browsers, they have their own methods to bind events.
W3C DOM
Obj. addEventListener (evtype, fn, useCapture) -- methods provided by W3C for adding event handlers. Obj is the object to add events. evtype is the event type without the on prefix. fn is the event processing function. If useCapture is true, the event processing function is executed in the capture phase, otherwise, the task is executed in the bubble stage.
Obj. removeEventListener (evtype, fn, useCapture) -- Methods for deleting event processing functions provided by W3C
Microsoft IE Method
Obj. attachEvent (evtype, fn) -- method provided by IE to add event handler functions. Obj is the object to add events, evtype is the event type, with the on prefix, fn is the event processing function, and IE does not support event capturing
Obj. detachEvent (evtype, fn,) -- method provided by IE for deleting event processing functions. evtype contains the on prefix.

Integration of the two methods

Function addEvent (obj, evtype, fn, useCapture) {if (obj. addEventListener) {obj. addEventListener (evtype, fn, useCapture);} else {obj. attachEvent ("on" + evtype, fn); // IE does not support event capture} else {obj ["on" + evtype] = fn; // In fact this situation does not exist} function delEvent (obj, evtype, fn, useCapture) {if (obj. removeEventListener) {obj. removeEventListener (evtype, fn, useCapture);} else {obj. detachEvent ("on" + evtype, fn);} else {obj ["on" + evtype] = null ;}}

There is a problem with the attach method of IE, that is, when using attachEvent, this points to the window rather than obj In the event handler function! Of course, there is a solution!

However, the attachEvent method of IE has another problem. The same function can be registered to the same event of the same object multiple times. Solution: discard the attachEvent method of IE! The attachEvent method in IE does not support capturing. It is not much different from traditional event registration (except for binding multiple event processing functions), and The attachEvent method in IE has a memory leakage problem!
AddEvent, delEvent modern edition

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 


Js event listening

<Input type = "button" value = "connect" onclick = "a ()"/>
<Script> function a () {alert (1) ;}</script>

Js listening event

<Table id = "table_id">
<Tr>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
</Tr>
<Tr>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
</Tr>
<Tr>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
</Tr>
<Tr>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
<Td> <p> 1, 1 </p> </td>
</Tr>
</Table>
<P> kkkkkkkkk </p>
<Script type = "text/javascript">
Var tb = document. getElementById ('table _ id') // you can use other methods to obtain this table.
Ps = tb. getElementsByTagName ("p "),
Trs = tb. getElementsByTagName ("tr ")

Trs. index = function (tr ){
For (var I = 0; I <this. length; I ++ ){
If (this [I] === tr) return I
}
}

For (var I = 0; I ...... remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.