Jquery fundamentals-(Part 5) jquery events

Source: Internet
Author: User
Basic Jquery tutorial

Author: Rebecca Murphey

Original link address http://jqfundamentals.com/

With contributions by James Padolsey, Paul Irish, and others. See the GitHub repository for a complete history of contributions.

Copyright 2011

 

Jquery event Overview

Jquery provides a simple method for appending event processors to the selection result. When an event occurs, the provided method is executed. Inside the method, this keyword points to the clicked element.

For details about the jqueyr event, visit the http://api.jquery.com/category/events.

The event processing function can receive an event object. This object can be used to determine the characteristics of the event and prevent the default behavior of the event.

Get details about the event object and access the http://api.jquery.com/category/events/event-object.

Associate events and elements

Jquery provides convenient methods for most common events. These methods will be the most commonly used in the future. These methods include: $. fn. click, $. fn. focus, $. fn. blur, $. fn. change, and so on -- for jquery's $. fn. the bind method is a shorthand method. When you want to provide data to the event processor, when you use client events, or when you want to pass an object with multiple events and multiple processing methods, the Bind method is very useful for binding the same processing method to multiple events.

Example 5.1: bind an event using a simple method

$('p').click(function() {    console.log('click');});

Example 5.2: bind an event using the $. fn. bind Method

$('p').bind('click', function() {    console.log('click');});

Example 5.3: bind a method with data through the $. fn. bind Method

$('input').bind(    'click change',  // bind to multiple events    { foo : 'bar' }, // pass in data    function(eventObject) {        console.log(eventObject.type, eventObject.data);        // logs event type, then { foo : 'bar' }    });
Link One-time execution event

Sometimes you need to execute a special processing method only once. If you want to do not execute the processing method, or you want to execute a different processing method. Jquery provides the $. fn. one method for this purpose.

Example 5.4: use $. fn. one to convert the processing method

$('p').one('click', function() {    console.log('You just clicked this for the first time!');    $(this).click(function() { console.log('You have clicked this before!'); });});

The $. fn. one method is particularly useful when you need to perform complex settings when an element is clicked for the first time, and subsequent clicks do not happen.

Detach events

You can use the $. fn. unbind method and pass the event type to separate an event and the processing method. If you add a function with a name to an event, you can pass it as the second parameter to separate the event.

Example 5.5: Remove all click events in the selected result.

$('p').unbind('click');

Example 5.6: Remove a specific click Processing Method

var foo = function() { console.log('foo'); };var bar = function() { console.log('bar'); };$('p').bind('click', foo).bind('click', bar);$('p').unbind('click', bar); // foo is still bound to the click event
Nameevent Space

In some complex applications and some controls shared with others, in order to prevent unexpected events that you do not know or are not able to understand, an error is removed. It is very useful to set namespaces for events.

Example 5.7: nameevent Space

$('p').bind('click.myNamespace', function() { /* ... */ });$('p').unbind('click.myNamespace');$('p').unbind('.myNamespace'); // unbind all events in the namespace
Bind multiple events

In your application, multiple events are often bound to an element, and each function has a different function to process events. In this case, you can pass an object that contains one or more key-value pairs to $. fn. bind. The key in the object is the event name value, which is the function for processing the event.
Example 5.8: bind multiple events

$('p').bind({    'click': function() { console.log('clicked!'); },    'mouseover': function() { console.log('hovered!'); }});

Note:

The preceding method is introduced only in jquery1.4.4.

Internal event processing functions

As mentioned in the overview, the event processing function receives an object that contains many attributes and methods. In most cases, event objects are used to block default actions of events by default blocking methods. Event objects contain a large number of other useful attributes and methods, including:

PageX, pageY

When an event occurs, the cursor is relative to the position in the upper left corner of the page.

Type

Event Type (for example, "click ")

Which

Pressed button or button

Data

Any data imported when an event is bound

Target

DOM element for initiating an event

PreventDefault ()

Prevent default actions of events

StopPropagation ()

Prevents event bubbles to other elements

 

In addition to the event object, the event handler can also use the keyword "this" to access the DOM elements bound to the handler. To apply the jquery method, we can convert the DOM element into a jquery object by using $ (this), as shown below:

var $this = $(this);

Prevent link Tracing

$('a').click(function(e) {    var $this = $(this);    if ($this.attr('href').match('evil')) {        e.preventDefault();        $this.addClass('evil');    }});
Trigger event Processor

Jquery provides a processor that triggers the binding to an element through $. fn. trigger without user operations. When this method is used, you cannot simply call the bound function as the click processor. Instead, you should store the function you want to call in a variable, and then pass the variable name when you bind it. Then you can call the function itself without the need for $. fn. trigger.

Correct trigger event Processor

var foo = function(e) {    if (e) {        console.log(e);   } else {        console.log('this didn\'t come from an event!');    }};$('p').click(foo);foo(); // instead of $('p').trigger('click')
Improve performance through event Delegation

In development, you will often add new elements to the item Page. When you do this, you may also need to bind events to these elements at the same time-these events are originally bound to elements on the page. You do not need to bind events every time you add new elements. Instead, you can use event delegation to solve the problem. Bind an event to a container element through event delegation. Then, when an event occurs, find the element containing it. If you think this sounds complicated, don't be afraid. jquery provides the $. fn. live and $. fn. delegate methods to make it easier.

Most people find that after adding elements to the page through event delegation, this method will improve the program performance even if you do not add elements to the page. Binding hundreds of event processors to individual elements becomes a simple small case. If you have a large number of elements, you should consider entrusting related events to container elements.

Note:

$. Fn. live method was introduced in jquery1.3, when only a few specific event types are supported. By jquery1.4.2, the $. fn. delegate method can be used, and it is a better method.

Event delegation through $. fn. delegate

$('#myUnorderedList').delegate('li', 'click', function(e) {    var $myListItem = $(this);    // ...});

Delegate events through $. fn. live

$('#myUnorderedList li').live('click', function(e) {    var $myListItem = $(this);    // ...});
Unbind delegated events

If you need to remove delegated events, you can easily remove them. Correspondingly, use $. fn. undelegate to unbind the event delegate bound to $. fn. delegate, and use $. fn. die to unbind the event delegate bound to $. fn. live. When binding, You can freely pass the name of the bound function.

Unbind event Delegate

$('#myUnorderedList').undelegate('li', 'click');$('#myUnorderedList li').die('click');
Event help tools

Jquery provides two event-related help functions, which will save you a lot of sound when you press the keyboard.

$. Fn. hover

The $. fn. hover method allows you to execute one or two functions when an element triggers the mouse to enter or exit the event. If you pass a function for execution, the function will be bound to two events at the same time. If you pass two functions, the first function will be bound to the mouse to enter the event, the second event is bound to the mouse removal event.

Note:

Before jquery1.4, the $. fn. hover method requires two functions.

Hover help functions

$('#menu li').hover(function() {    $(this).toggleClass('hover');});
$. Fn. toggle

The $. fn. toggle method is triggered by the click Event and receives two or more functions. Each time a click event occurs, the bound event queue is executed in sequence. Generally, $. fn. toggle receives two functions, but it has time to receive an infinite number of functions. Therefore, be very careful, especially when too many function queues are being debugged.

Toggle help functions

$('p.expander').toggle(    function() {        $(this).prev().addClass('open');    },    function() {        $(this).prev().removeClass('open');    });
Create an input prompt for exercise (hint)

(The address below is based on the beginning of the article to the original article address, that is, the http://jqfundamentals.com /)

Open the/exercises/index.html file in the browser. Use/exercises/js/inputHint. js or Firebug. Your task is to create "hint" text for the search input using the input tag (Chinese. The procedure is as follows:

1. Add the search input value to the text of the label element.

2. Add a class named "hint" to the search input.

3. Remove the label element.

4. Bind a focus event to the search input to remove the text and class of the hint.

5. Bind a blur event to the search input to store the hint text. If there is no text, store the hint class.

If you are implementing this function for a real website, think about other things to consider.

Add Tag navigation

Open/exercises/index.html in the browser. Use/exercises/js/tabs. js. Your task is to create a tag navigation for the two div module elements. Implementation:

1. Hide all modules

2. Create an unordered list element before the first module.

3. Use $. fn. each to traverse the module. For each module, use the text in the h2 element label as each text you add to the unordered list

4. Bind a click event to the list item:

1) display relevant modules and hide other modules

2) Add a "current" class to the clicked list item

3) remove the "current" Class of other list items

5. display the first tag.

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.