Events are raised when a user operates on a page or when a page is loaded to complete javascript and HTML The interaction between . Common element click events 、 Mouse events 、 Keyboard input events, etc , Comparative biography Javascript

comparison JQuery The basic event handling mechanism has been added and extended , Greatly enhance the ability of event processing .

One 、DOM Loading event

After loading the page, the browser will go through javascript by Dom Element loading events , Use Javascript It's when you use window.onload Method , and Jquery It uses $(document).ready() Method , The following table

Show the similarities and differences between the two events .

   window.onload Method  $(document).ready() Method
  Execution opportunity   You have to wait for everything to load before you can execute   Page DOM After the element is drawn, it can be executed without waiting for all the contents to be loaded .
The number of bound functions

This method can bind a function , If you bind multiple only Can execute the last binding . example :



The execution result only executes the last bound function, and the result is print :2.

  Be able to register multiple functions , Execute binding functions in binding order . example :



The execution result is the sequential execution of bound functions : Print first 1. And then print it 2.

  Simplify writing   nothing  $().ready();$.ready()

Two 、 Event handling

When the file is loaded, you can add event handling to the element , Then the event performs some actions to complete the related operations .jquery There are many ways to handle events in , There are mainly bind()、one()、unbind()、live()、trigger()、triggerHander() etc. .Jquery Methods use bind() Method to make a specific event binding for the matched elements .bind() The format of the method is as follows :

bind(type,[ data],fun);

bind() The method has three arguments , The parameters are described as follows :

The first parameter is the event type , Mainly as follows :blur、focus、load、resize、scroll、unload、click、dbclick、mousedown、mouseup、mousemove、mouseover、mouseout、mouseenter、mouseleave、change、select、submit、keydown、keypress、keyup and error etc. . It can also be a custom name ,Jquery The event binding type in is better than javascript Less "on", therefore jquery Middle event click Corresponding javascript Medium onclick function .

The second parameter is optional , As Property values are passed to the event object's extra data object .

The third parameter is the handler for binding .

Binding click event examples for buttons :

<input type="button" id="btn1" value=" single click ">

$("#btn1").bind("click",function(){alert(" Click event binding ");});

bind() Method is valid until unbind() Methods or delete elements . If you want to bind events only once, use one() Method binding event .one() Same as bind() The method is the same , The difference lies in one() Method bound events can only be executed once .

Binding one-time event examples for buttons :

<input type="button" id="btn1" value=" single click ">

$("#btn1").one("click",function(){alert(" Click event binding ");});

unbind() Method to unbind an event for an element ,unbind() The format of the method is as follows :


unbind() Methods are elements bind() Method , Remove the bound event from each matching element . Delete all binding events when there are no parameters . If an event type parameter is provided, the specified binding event is deleted . If the event type is specified , If the second parameter specifies the function name, the event corresponding to the second parameter name in the event type will be deleted .

Example :

<input type="button" id="btn1" value="click" />

<input type="button" id="btn2" value="removeBind" />

$("#btn1").bind("click", fun1 = function () { alert(" event 1"); });

$("#btn1").bind("click", fun2 = function () { alert(" event 2"); });

$("#btn2").bind("click", function () {
$("#btn1").unbind("click", fun2);

This example uses unbind() Method to remove the second bound event handler .

live() Method to dynamically bind events to elements , After binding events with this method , Adding a new corresponding element can also trigger corresponding events .live() The format of the method is as follows :


 live Dynamic binding example :


This example is for all p The element node dynamically adds click event , Whether it's existing p The element node will be added later p Element nodes are triggered when they are clicked hide() To hide yourself .die() The method is live() Method , result live() Method to dynamically bind events and unbind() The method is the same . Use die() Method after dynamic binding , All dynamically bound events will be deleted .

trigger() Method triggers the event in the parameter on the matched element , This method triggers the browser default event , return false Block browser default Events .trigger() The format of the method is as follows :


trigger() Method example :


This example triggers the first from Form submit operation .

triggerHandler() Method that triggers binding events , But it doesn't trigger browser default Events . And trigger() Method is triggered and returns false The effect is the same . Usage and trigger equally .

3、 ... and 、 event

The main event types listed in event handling are as follows :blur、focus、load、resize、scroll、unload、click、dbclick、mousedown、mouseup、mousemove、mouseover、mouseout、mouseenter、mouseleave、change、select、submit、keydown、keypress、keyup and error etc. . Each event type is mainly used in two ways to bind events 、 Triggering event . With click Event as an example ,click The format of the method is as follows : The binding event $(selector).click(functiron(){// The body of the function }), Triggering event $(selector).click(). example :

<input type="button" id="btn1" value=" The binding event "/>

<input type="button" id="btn2" value=" Triggering event "/>

$("#btn1").click(function(){alert(" Event binding ");});


This example is the first button btn1 The binding event , Is a button btn2 The binding event also triggers the binding event of the first button in the binding event . Other event types and click similar .

Four 、 Composite event

Synthetic events, also known as interactive events, are JQuery Custom methods , There are two ways hover() and toggle().

hover() Method to simulate mouse over events , The format of the method is as follows :hover(enter,leave). example :

$("ul li").hover(function(){alert("Enter");},functiron(){alert("leave");});

The example is ul Of li Element binding hover event , When the mouse stops ul Child elements li It's going to trigger enter() function , Print “Enter”, When the mouse moves out li When will the element print "leave".

toggle() Method switch operation loop to execute bound function , The format of the method is as follows :toggle(fun1,fun2,...,funN); example :

<input type="button" id="btn1" value=" Trigger switch operation "/>

$("#btn1").toggle(function(){alert(" Start ");},function(){alert(" continue ");},function(){alert(" end ");});

The example is a button btn1 Each click of the binding switch event triggers one of the binding events in sequence . The example clicks print for the first time " Start ", Second click Print " continue ", Third click Print " end ", Click again to print just like the first time " Start ", Loop order execution function .

5、 ... and 、 Event properties

Jquery The event attribute is encapsulated, so that the event processing can run normally in all browsers without distinguishing the type . The properties of each event are as follows :

Event type event.type. This property is used to get the type that triggers the event , Different operations that do not raise events return different results ; example :


This example returns the element p Click the event type of the event , The result is "click";

Event type This property is used to get the element that triggers the event ; example :


This example returns the element a Of href attribute .

Event default behavior event.preventDefault; This property is used to block the default property of the event , example :


Use this attribute to block the element a The default jump behavior of , Results and return false equally .

Event Bubbling event.stropPropagation Property to prevent event bubbling , example :

$("div").click(function(event){alert(" Inside click ");event.stopPropagation;});

In this example stopPropagation Property block div Of the parent element click Event is triggered .

event.pageX and event.pageY attribute , Use these two properties to get the current position of the mouse relative to the page . example :

$("p").click(function(event){alert("current mouse location  "+event.pageX+" "+event.pageY);});

This example is when you click on the element p To get the current position of the mouse , And print it out .

event.witch attribute , Use this property to get the left, middle and right mouse buttons when you click , Get key values in keyboard events .


This example prints the mouse key value when the mouse is pressed . The corresponding values of the left, middle and right keys are 1、2、3.

event.metaKey Property is used to get the keyboard's ctrl key , example :

$("body").keydown(function(event){if(event.metaKey){alert("ctrl");}else{alert("no ctrl");}});

In this example, when you press the keyboard in the page, if the key is ctrl Key to print ctrl, Otherwise print "no ctrl".

6、 ... and 、 Event Bubbling

There are multiple binding events in the page, so multiple elements may appear in response to the same event , This led to events that we didn't expect , This phenomenon is the bubbling of events , To deal with this problem, we can limit the scope of the event ,Jquery Middle make stopPropagation() Method to stop bubbling of events . Event bubble example :

<body><div><span> Event Bubbling </span>div Content </div>body Content </body>


$("body div").click(function(){alert("div");});


In this example, when you click span Three print events will be triggered "span" "div" "body", How to prevent events from bubbling ? have access to Jquery In the event stropPropagation() Method to stop event bubbling . Change the above example to this :


$("body div").click(function(event){alert("div");event.stopPropagation();});


So when you click on different elements, there will be no bubbling .

7、 ... and 、 Event namespace

Adding event name space is convenient for event management : Delete events and trigger events . example :

<div> Element binding multiple events </div>





Because of the use of a namespace, you can delete events in the specified namespace , Remove all plugin The method of event function under namespace is as follows :$("button").click(function(){$("div").unbind(".plugin");}); This removes all the namespace that is plugin Event function of .div Only... Is left click and dbclick The binding event .

Using a namespace makes it easy to trigger specific events , If div Bound two click event , One with a namespace and one without a namespace . If you want to trigger events that are not included in the namespace, you can use trigger("click!") Method ,! The exclamation point is used to match all the click Method .

Jquery More articles on basic event operations

  1. jQuery Basic events

    jQuery The basic event method , Here's the picture : Code implementation : <script src="JS/jquery-1.12.4.min.js"></script> <s ...

  2. 【 Summarize and organize 】JQuery Based on learning --- Events

    jQuery Mouse events click And dbclick event In interactive operation , The most simple and direct operation is click operation .jQuery There are two ways. One is click Method is used to listen for user click operations , Another way is dbclick Method is used for ...

  3. Jquery The foundation DOM operation

    from : JQuery Medium DOM The operation mainly includes : build [ newly build ]. increase [ add to ]. Delete [ Delete ]. Change [ modify ]. check [ lookup ][ Like data ...

  4. Jquery Basic animation operation

    Jquery Can easily add animation effects to the web page , Bring new vitality to the web . One .show() Methods and hide() Method show() Methods and hide() The method is jquery The most basic animation method in . Use show() ...

  5. jQuery Basic notes event (6)

    day56 Reference resources : event *****         1. The binding we've learned so far ...

  6. JQuery Basics and events and animation

    JQuery grammar  1.JQuery(" Selectors ").action; Call the time function through the selector   but Jquery It can be used $ Symbol instead of , namely $(" Selectors ").action; ① ...

  7. jquery api common Event operations

    change.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html ...

  8. jQuery Basics -- Music video operation

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  9. Jquery Event operation and document operation of

    For those familiar with front-end development , Believe in Jquery It must be no stranger , be relative to JavaScript The red tape ,Jquery More concise , Of course, simplicity doesn't mean simplicity , We can use Jquery Complete all the functions we want to achieve , This is for Xiaobai ...

Random recommendation

  1. Linux Commonly used instructions ---$PATH ( environment variable )

    Instance of a : Set temporary environment variables stay linux Set temporary environment variables on the server , When to exit shell Environmental time , Automatically destroy export JAVA_HOME=/usr/java/jdk1.6.0_32 export class ...

  2. WITH+HInt MATERIALIZE Not necessarily effective

    The one that needs to be materialized after multiple calls . Call it once , Materialization doesn't work MATERIALIZE  grammar :MATERIALIZE  describe : Instructs the optimizer to materialize inline views ———— A view based temporary table is created during execution . with dd ...

  3. Reliability diagrams

    Reliability diagrams (Hartmann et al. 2002) are simply graphs of the Observed frequency of an event ...

  4. 20165236 《Java Programming 》 Week 7 learning summary

    20165236 <Java Programming > Week 7 learning summary Summary of the learning content of the textbook Chapter 11  JDBC And MySQL database 1.MySQL Database management system : MySQL Database management system , abbreviation MySQL, yes ...

  5. Codeforces 629 E. Famil Door and Roads

    Topic link : Ask about the expectations of this simple ring . Consider splitting this ring into two parts . Make ${deep[x]>=deep[y]}$ ...

  6. scrapy Reptile series 3 -- Crawl the image and save it locally

    The function point : How to crawl pictures , And save to local Crawl to the website : Matador anchor Complete code : Main code : im ...

  7. UVA-806 Spatial Structures ( Quartertree )

    The main idea of the topic : The black spot on an image is converted between two representations . Topic analysis : Recursion ... Be careful : Pay attention to the details when outputting !!! The code is as follows : # include<iostream> # include<c ...

  8. Clever use of Web Developer Tools F12 review 、 Modifying elements 、 Remove the ads 、 The shield

    Clever use of Web Developer Tools F12 review . Modifying elements . Remove the ads . The shield Whenever you open a web page , Is there a lot of advertising on the page : Whether to operate the page ( For example, watch Super Clear Video ), Please register and log in first : Whether to lock the video page ...

  9. Module definition file .def

    One function DLL There are two ways to declare exported functions in : One is to add... To the function declaration __declspec(dllexport), There is no more example of : Another way is to use module definition (.def) File statement ,.def The file provides the linker with ...

  10. Elaborate PHP Of FPM

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Basic concepts ++ C ...