jQuery event binding and JavaScript native event binding

jQuery event binding

jQuery provides four binding methods for event monitoring, namely bind and on.

The corresponding functions to release the monitoring are unbind and off respectively.

 

bind(event,[data],function)

Bind is the most frequently used one, and its function is to bind a listener function of a specific event type to the selected element. The meaning of the parameters is as follows:

event: event type, such as click, change, mouseover, etc.

data: The parameters passed into the monitoring function are retrieved through event.data. Optional

function: monitor function, you can pass in event object, where event is the event object encapsulated by jQuery, which is different from the original event object, so you need to pay attention to it when using it

use:$("#div li").bind("click",myFun);

 

on(event,childSelector,data,function)

The on() method adds one or more event handlers to the selected elements and child elements. The most commonly used

Since jQuery version 1.7, the on() method is a new alternative to the bind(), live() and delegate() methods. This method brings a lot of convenience to the API, we recommend this method, it simplifies the jQuery code base.

Note: The event handlers added using the on() method are applicable to current and future elements (such as new elements created by scripts).

Tip: To remove the event handler, please use the off() method.

Tip: To add an event that only runs once and then remove it, please use the one() method.

event: required. Specifies one or more events or namespaces to be removed from the selected element. Multiple event values ​​are separated by spaces, and it can also be an array. Must be a valid event.

childSelector: Optional. Specifies event handlers that can only be added to the specified child element (and not the selector itself, such as the deprecated delegate() method).

 data: optional. Specifies the additional data passed to the function.

function: optional. Specifies the function to run when the event occurs.

使用:$(selector).on(event,childSelector,data,function);

.click(), .trigger() also have event binding effects

 

JavaScript native event binding

1. Direct binding in DOM elements: DOM elements here can be understood as HTML tags. JavaScript supports directly binding events in tags

2. OnXXX binding in JavaScript code: Binding events in JavaScript code can separate JavaScript code from HTML tags, and the document structure is clear, which is convenient for management and development.

3. Binding event listener function: Another way to bind events is to use addEventListener() or attachEvent() to bind the event listener function.

 

1. Direct binding in DOM elements

1. Native functions

1 <input οnclick="alert('Thank you for your support')" type="button" value="Click me" />


2. Custom functions

Copy code

 1 <input οnclick="myAlert()" type="button" value="点我" />
 2 
 3 <script type="text/javascript">
 4 
 5   function myAlert(){
 6 
 7     alert("谢谢支持");
 8 
 9   }
10 
11 </script>

Copy code

 

2. OnXXX binding in JavaScript code

The syntax for binding events in JavaScript code is:

elementObject.onXXX=function(){

    // event handling code

}

Among them:

  • elementObject is a DOM object, that is, a DOM element.
  • onXXX is the name of the event.


For example, bind an event to the button with id="demo" and display its type attribute:

Copy code

1 <input id="demo" type="button" value="click me to show the type attribute" /> 
 2 
 3 <script type="text/javascript"> 
 4 
 5 document.getElementById("demo").οnclick= function(){ 
 6 
 7 alert(this.getAttribute("type")); // this refers to the HTML element of the current event, here is the <div> tag 
 8 
 9} 
10 </script>    

Copy code

 

Three. Binding event listener function

addEventListener() function syntax:

elementObject.addEventListener(eventName,handle,useCapture);

parameter Description
elementObject DOM objects (ie DOM elements).
eventName The name of the event. Note that there is no "on" in the event name here, such as the mouse click event click, the mouse double click event doubleclick, the mouse move-in event mouseover, the mouse move-out event mouseout, etc.
handle Event handler function, that is, the function used to handle the event.
useCapture Boolean type, whether to use capture, generally use false. This involves the concept of JavaScript event flow, which will be explained in detail in subsequent chapters.


attachEvent() function syntax: (compatible with IE)

elementObject.attachEvent(eventName,handle);

parameter Description
elementObject DOM objects (ie DOM elements).
eventName The name of the event. Note that unlike addEventListener(), the event name here has "on", such as mouse click event onclick, mouse double click event ondoubleclick, mouse move in event onmouseover, mouse move out event onmouseout, etc.
handle Event handler function, that is, the function used to handle the event.

 

Note: The event handler function refers to the "function name" without parentheses.


addEventListener() is a standard method of binding event listener functions, supported by W3C, Chrome, FireFox, Opera, Safari, IE9.0 and above versions all support this function;

However, IE8.0 and below versions do not support this method, it uses attachEvent() to bind the event listener function. Therefore, this method of binding events must deal with browser compatibility issues.

The following code for binding events has been processed for compatibility and can be supported by all browsers:

Copy code

1 function addEvent(obj,type,handle){ 
 2 
 3 try{ // Chrome, FireFox, Opera, Safari, IE9.0 and above 
 4 
 5 obj.addEventListener(type,handle,false); 
 6 
 7 }catch( e){ 
 8 
 9 try{ // IE8.0 and below 
10 
11 obj.attachEvent('on' + type,handle); 
12 
13 }catch(e){ // early browser 
14 
15 obj['on '+ type] = handle; 
16 
17} 
18 
19} 
20 
21}                    

Copy code

Here try{ ...} catch(e){ ...} is used instead of if ... else... statements to avoid browser error prompts.

For example, to bind an event to a button with id="demo", a dialog box will pop up when the mouse is clicked:

 

Copy code

1 var obj = document.getElementById("demo"); 
2 addEvent(obj ,"click",myAlert); 
3 
4 function myAlert(){ 
5 
6 alert("I am a dialog box"); 
7 
8}

Copy code

 

 

The difference between jQuery event binding and JavaScript event binding

The event binding in jQuery is superimposable, and the event binding in JavaScript is overridable.

Take a look at the sample code:

Copy code

 1  /* jQuery 绑定事件 */ 
 2  $(".cnd").click(function(){  
 3     console.log("first")}  
 4   );  
 5  $(".cnd").click(function(){  
 6     console.log("second")}  
 7   );  
 8     
 9  $(".cnd").click(function(){  
10     console.log("3rd")}  
11   );  
12     
13  /* js 绑定事件 */
14  var cm2 = document.getElementById("me2");  
15  cm2.οnclick=function(){  
16       console.log("first");  
17  };  
18   cm2.οnclick=function(){  
19       console.log("second");  
20   };  
21   cm2.οnclick=function(){  
22       console.log("3rd");  
23   };  

Copy code

 

Execute the .cnd click event of jQuery, the console prints:

 

Execute the cm2 click event of js, what the console prints is:

 

It can be found:

Using jQuery's event binding method, three processing functions are bound to the click event of the same element, and the results are output in order, which shows that jQuery's event processing functions are superimposed;

Using JavaScript's native event binding, you can find that only the last same binding event is executed, and the event handler function bound later overwrites the previous event handler function.

 

Guess you like

Origin blog.csdn.net/AN0692/article/details/110439137