jquery-based event operations

Source: Internet
Author: User

An event is an interaction between JavaScript and HTML that is raised when a page or page loads when a user is operating. Common Elements Click events, mouse events, keyboard input events, etc., than the JavaScript

The ability to deal with events is greatly enhanced by increasing and extending the basic event handling mechanism compared to jquery.

One, Dom Load event

When the page is loaded, the browser loads events through JavaScript for DOM elements, using JavaScript with the Window.onload method, and jquery using $ (document). Ready () method, the following table

Show the similarities and differences between the two events.

Window.onload method $ (document). Ready () method
Timing of execution You must wait for all content to finish loading before you can execute After the page's DOM element is drawn, it can be done without waiting for all content to load.
Number of binding functions

The method can bind a function if it is bound to more than one can perform the last binding. Example:

Window.onload=function () {alert ("1");}

Window.onload=function () {alert ("2");}

Execution results only the last bound function results are printed: 2.

Ability to register multiple functions and execute binding functions in the binding order. Cases:

$ (document). Ready (Funtction () {alert ("1");});

$ (). Ready (function () {alert ("2");});

The execution result is a function that executes the binding sequentially: Print 1 First and then Print 2.

Simplified notation No $ (). Ready (); $.ready ()
Second, event processing

When the file is loaded, you can add event handling to the element, and the event performs some action to complete the action. There are several event handling methods in jquery, including bind (), one (), Unbind (), Live (), Trigger (), Triggerhander (), and so on. The jquery method uses the Bind () method to make a specific event binding for the matched element. The bind () method format is as follows:

Bind (type,[data],fun);

The bind () method has three parameters, each of which is 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. Or it can be a custom name, and the event binding type in jquery is "on" less than JavaScript, so the event click in jquery corresponds to the onclick function in JavaScript.

The second parameter is an optional parameter that is passed as an extra data object to the event object as the value of the Event.data property.

The third parameter is the handler function used to bind.

Example of a button-binding order-click event:

<input type= "button" id= "BTN1" value= "click" >

$ ("#btn1"). Bind ("click", Function () {alert ("clicking Event Binding");});

The bind () method is valid for an element-bound event until the Unbind () method or the element is deleted. Use the One () method to bind an event if you want the binding event to execute only once. One () is the same as the bind () method, except that an event that is bound by the single () method can only be executed once.

Example of a one-time event for button bindings:

<input type= "button" id= "BTN1" value= "click" >

$ ("#btn1"). One ("click", Function () {alert ("clicking Event Binding");});

The unbind () method cancels the event binding for the element, and the Unbind () method has the following format:

$ (selctor). Unbind ([Type],[data])

The unbind () method is the reverse operation of the element bind () method, removing the bound event from each matching element. Removes all binding events when there are no parameters. Deletes the specified binding event if a parameter of the event type is provided. If the event type is specified and the second parameter specifies the function name, the event that corresponds to the second parameter name is removed from the event type.

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);
});

The example removes the second bound event handler using the two parameter form of the Unbind () method.

The live () method dynamically binds an event to an element, and when the method binds the event, the new corresponding element can also trigger the corresponding event. The live () method format is as follows:

$ (selector). Live ([Type],[data],fun);

Live Dynamic Binding Examples:

$ ("P"). Live ("Click", Function () {$ (this). Hide ();});

The example dynamically adds a click event for all P element nodes, either an existing P element node or a P-element node to be added later to hide itself by clicking it at the midpoint. The die () method is the reverse operation of the Live () method, as a result of the live () method dynamically binding the same event as the Unbind () method. After dynamic binding using the Die () method, all dynamically bound events are deleted.

The trigger () method triggers the event in the parameter on the matched element, which triggers the browser default event, which returns false to prevent the browser from default. The trigger () method format is as follows:

$ (selector). Trigger ([Type],[data]);

Trigger () Method Example:

$ ("Form:first"). Trigger ("submit");

The example triggers a submit operation for the first from form.

The Triggerhandler () method triggers a binding event, but does not trigger a browser default event. The same as the trigger () method, which returns false after firing. Use the same method as trigger.

III. Events

The main event types are listed in event handling 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. The individual event types are mainly two usage binding events, triggering events. For the Click event, for example, the click Method is formatted as follows: Bind event $ (selector). Click (Functiron () {//function body}), triggering event $ (selector). Click (). Cases:

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

<input type= "button" id= "BTN2" value= "trigger event"/>

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

$ ("#btn2"). Click (function () {$ ("#btn1"). Click (); )

  The example btn1 a binding event for the first button, btn2 the binding event for the button and triggers the first button's binding event in the binding event. The remaining event types are similar to click.

Iv. Synthetic Events

Synthetic events can also be called interactive events, which are methods of jquery customization, with two hover () and toggle ().

The hover () method mimics the mouse hover event, in the following format: hover (enter,leave). Cases:

$ ("ul Li"). Hover (function () {alert ("Enter");},functiron () {alert ("Leave");});

This example binds the LI element of UL to the hover event, which triggers the ENTER () function when the mouse hovers over the UL sub-element Li, and prints "enter" when the mouse moves out of the LI element and "leave" is printed.

The toggle () method Toggles the function loop to execute the binding, as follows: Toggle (fun1,fun2,..., Funn);

<input type= "button" id= "BTN1" value= "trigger switch operation"/>

$ ("#btn1"). Toggle (function () {alert ("Start"),},function () {alert ("continue"),},function () {alert ("End");});

This example triggers one of the binding events in order for the button BTN1 bound toggle event to be clicked each time. The example first click Print "Start", the second click Print "Continue", the third click print "End", click again and the first time to print "Start", loop order execution function.

V. Event Properties

jquery encapsulates event properties so that event handling does not require a discriminant type to function under each browser. The individual event properties are as follows:

Event Type Event.type. This property is used to obtain the type that triggered the event, and returns different results for different operations that do not raise the event;

$ ("P"). Click (Function (event) {alert (event.type);});

The example returns the event type of the element p click event, and the resulting print is "click";

Event Type Event.target This property is used to get the element that triggered the event;

$ ("a"). Click (Function (event) {alert (event.target.href);});

The example returns the href attribute of element A.

Event default behavior Event.preventdefault; This property is used to block the default properties of an event, for example:

$ ("a"). Click (Function (event) {event.preventdefault;});

Use this property to block the default jump behavior of element A, and the result is the same as return false.

The event bubbling Event.stroppropagation property is used to block event bubbling, for example:

$ ("div"). Click (Function (event) {alert ("inner click"); event.stoppropagation;});

The example uses the Stoppropagation property to block the Click event of a div's parent element from being triggered.

Event.pagex and Event.pagey Properties, use these two properties to get the current position of the mouse relative to the page. Cases:

$ ("P"). Click (Function (event) {alert ("Current mouse location" +event.pagex+ "" +event.pagey);});

This example gets the current position of the mouse when the element p is clicked and prints it out.

The Event.witch property, which uses this property to get a mouse click on the left and right mouse button, gets the key value in the keyboard event.

$ ("P"). MouseDown (function (event) {alert (event.witch);});

This example prints the mouse key value when the mouse is pressed. The corresponding values for the left and right Jian are 1, 2, and 3 respectively.

The Event.metakey property is used to get the CTRL key of the keyboard in an event, for example:

$ ("Body"). KeyDown (function (event) {if (Event.metakey) {alert ("Ctrl");} Else{alert ("No Ctrl");});

This example prints "No Ctrl" If you press the CTRL key while pressing the keyboard in the page.

Vi. Event Bubbling

There are multiple binding events on the page so there may be multiple elements responding to the same event, which raises the event that is not what we expected, this is the event bubbling, to deal with this problem can limit the scope of the event, jquery makes Stoppropagation () method to stop the bubbling of events. Event Bubbling Example:

<body><div><span> event bubbling </span>div content </div>body content </body>

$ ("Body"). Click (function () {alert ("Body");});

$ ("Body div"). Click (function () {alert ("div");});

$ ("span"). Click (function () {alert ("span");});

In this example, when you click Span, three print events "span" "div" "body" are triggered, how do I block event bubbling? You can use the Stroppropagation () method in the jquery event to stop event bubbling. The above example changes to this:

$ ("Body"). Click (Function (event) {alert ("body"); Event.stoppropagation ();});

$ ("Body div"). Click (Function (event) {alert ("div"); event.stoppropagation ();});

$ ("span"). Click (Function (event) {alert ("span"); event.stoppropagation ();});

This will not happen when you click on different elements.

Vii. Event Namespaces

Event add namespace facilitates management of events: Delete events and trigger events. Cases:

<div> element Binding Multiple Events </div>

$ ("div"). Bind ("Click.plugin", function () {alert ("Click.plugin");});

$ ("div"). Bind ("click", Function () {Alert ("click");});

$ ("div"). Bind ("Mouseover.plugin", function () {alert ("Mouseover.plugin");});

$ ("div"). Bind ("Dbclick", function () {alert ("Dbclick");});

Because namespaces can be used to delete events in the specified namespace, such as removing all the event functions under the plugin namespace, the method is as follows: $ ("button"). Click (function () {$ ("div"). Unbind (". Plugin");}); This removes all the namespaces that are plugin event functions. Only the Click and Dbclick binding events are left in the Div.

Using namespaces is handy for triggering specific events, such as two click events for a Div, and one with namespaces without namespaces. If you want to trigger an event that is not included in the namespace, you can use trigger ("click!") Method! The action of an exclamation mark is to match all the click methods that are not contained in the namespace.

jquery-based event operations

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.