JQuery event usage example _ jquery

Source: Internet
Author: User
This article mainly introduces jQuery event usage instance summary, and makes a more detailed instance analysis on Event binding and usage of various events, which has good reference value, if you need it, you can refer to this article to detail the event usage in jQuery in the form of examples, which provides a good reference value for jQuery learning. Share it with you for your reference. The usage is as follows:

1. bind an event to the element using the method name:

$('li').click(function(event){})

2. bind events to elements using the bind method:

$('li') .bind('click',function(event){}) .bind('click',function(event){}) 

It can be seen that through bind, you can bind multiple events to the element.

3. namespace of the event

Why do we need an event namespace?

→Assume that two click events are bound to the li element first.

$('li') .bind('click',function(event){}) .bind('click',function(event){}) 

→ Now we want to cancel one of the click events, which may be written as follows:

$('li').unbind('click')

But in this way, all the click events of li are canceled, which is not what we want. You can use the event namespace to solve this problem. The event namespace is required because it facilitates the cancellation of events.

How to Use the event namespace?
→ When binding an event to an element, add a namespace after the event name. The format is as follows: event name. namespace name.

$('li') .bind('click.editMode',function(event){}) .bind('click.displayMode',function(event){}) 

→ When canceling an event, you can write as follows:

$('li').unbind('click.editMode')

4. event types

Blur
Change
Click
Dblclick
Error
Focus
Focusin
Focusout
Keydown
Keypress
Keyup
Load
Mousedown
Mouseenter
Mouseleave
Mousemove
Mouseout
Moseover
Mouseup
Ready
Resize
Scroll
Select
Submit
Unload

5. one method

Used to create a one-time event. Once this event is executed once, it will be automatically deleted.

$("p").one("click",function(){ $(this).animate({fontSize: "+=6px"});})

6. delete an event

// Add an event $ ("p") to the element first "). click (function () {$ (this ). slideToggle () ;}) // Delete the element event $ ("button "). click (function () {$ ("p "). unbind ();})

7. Event attributes

Actually, it is the global attribute of jquery, jQuery. Event. Whenever an Event is triggered, the Event object instance is passed to Event Handler.

You can use the Event constructor to create an Event and trigger the Event.

var e = jQueery.Event("click")jQuery("body").trigger(e);

You can even put an anonymous object in the Event through the constructor.

var e = jQuery.Event("keydown", {keyCode : 64});jQuery("body").trigger(e);

You can use event. data. KeyCode to obtain the value of an anonymous object.

You can use the jQuery. Event constructor to put anonymous objects in the Event for transmission. In addition, you can also pass anonymous objects through events.

$("p").click({param1 : "Hello", param2 : "World"}, someFunction);function someFunction(event){ alert(event.data.param1); alert(event.data.param2);}

You can obtain the key of an anonymous object through event. data.

You can also obtain other information through the Event object instance, such:

$("p").click(function(event){ alert(event.target.nodeName);})

Use event.tar get. nodeName to obtain the element name of the trigger event.

Other attributes of jQuery. Event include:

AltKey: If the alt key is pressed, it is true. In the Mac keyboard, the alt key is marked as Option.
CtrKey ctrl is pressed
The shiftKey Shift key is pressed.
Current element of the currentTarget bubble stage
Data
MetaKey generally uses the Meta key As Ctrl, while the Mac key as the Command key.
Horizontal coordinates of the pageX mouse event time mark relative to the page Origin
The vertical coordinate of the pageY mouse event time mark relative to the page Origin
RelatedTarget: elements that trigger mouse events when the cursor leaves or enters
Horizontal coordinates of the screenX mouse event time mark relative to the screen Origin
The vertical coordinate of the screenY mouse event time mark relative to the screen Origin
Result returns the last non-undefined value from the previous event processor.
Elements of the target trigger event
Timestamp jQuery. Event timestamp when an instance is created, in milliseconds
Type event type, such as click
If it is a keyboard event, which indicates the number of the key. If it is a mouse event, it indicates that the key is left, right, or right.

8. Event Method

Event. preventDefault () blocks default behavior
Event. stopPropgation () Stop "Bubbling", that is, stop further propagation along the DOM
Event. stopImmediatePropagation () stops further propagation of all events
Event. isDefaultPrevented ()
Event. isPropgationStopped ()
IsImmediatePropgagationStopped ()

9. live and on methods

This method allows us to create events for nonexistent elements. Unlike the bind method, you can bind events to all matching elements and set those elements that do not exist yet and need to be dynamically created. In addition, the live method does not have to be placed in $ (function () {}) Ready processor. After getting to jQuery 1.7, we changed it to the on method.

$("p").on("click", function(){ alert("hello");})

To cancel registration:

$("button").click(function(){ $("p").off("click");})

10. trigger Method

You can use the trigger method to manually trigger events bound to elements.

$("#foo").on("click",function(){ alert($(this).text());})$("#foo").trigger("click");

You can also specify input parameters when binding events and input real parameters when a trigger event occurs.

$("#foo").on("custom", function(event, param1, param2){ alert(param1 + "\n" + param2)})$("#foo").trigger("custom",["Custom","Event"]);

Trigger triggers an instance created by jQuery. Event:

var event = jQuery.Event("logged");event.user = "foo";event.pass = "bar";$("body").trigger(event);

You can even input an anonymous object when trigger a method:

$("body").trigger({ type: "logged", user: "foo", pass: "bar"});

To stop triggering Event propagation, you can use the stopPropgation () method of the jQuery. Event instance or return false in any Event.

11. triggerHandler Method

The triggerHandler method differs from the trigger method in that the triggerHandler method does not execute the default event of an element or "bubble ".

// Bind a focus event to an element $ ("input "). focus (function () {$ ("Focused "). appendTo ("# id "). fadeOut (1000);}) // trigger with triggerHandler $ ("# id "). click (function () {$ ("input "). triggerHandler ("focus"); // does not trigger the default focus action, that is, enter the text box}) // trigger $ ("# id") with trigger "). click (function () {$ ("input "). trigger ("focus"); // triggers the default and bound behavior of foucs at the same time })

12. Event bubbling and event Delegation

What is event bubbling?

There is such a piece of code.

 

I am a Link!

I am another Link!

Now, bind a click event to all elements of the page, including window and document.

  $(function () {   $('*').add([document, window]).on('click', function(event) {    event.preventDefault();    console.log(this);   });  });

When you click any element on the page, the click event will start from the current element and spread to the upper-level element until the top-level element. Here is the window.

How to Prevent event bubbles?

Obviously, only a specific event is expected to occur on a specific element, rather than event bubbling. At this time, we can bind events to a specific element.

  $(function () {   $('a').on('click', function(event) {    event.preventDefault();    console.log($(this).attr('href'));   });  });

Above, only the click event is bound to a without it.

How to effectively use event bubbling?

In jquery, event delegation makes good use of event bubbles.

  • Item #1
  • Item #2
  • Item #3
  • Item #4

Now, we want to bind an event to the tag of the existing li, and write as follows:

$( "#list a" ).on( "click", function( event ) { event.preventDefault(); console.log( $( this ).text() );});

But what if I add new li and a to the existing ul?

$( "#list" ).append( "
  • Item #5
  • " );

    As a result, click a in the newly added li. Nothing happens. So how to bind events to dynamically added elements?

    If we can bind an event to a's parent element, the Child-level dynamic element generated within the parent element will also bind the event.

    $( "#list" ).on( "click", "a", function( event ) { event.preventDefault(); console.log( $( this ).text() );});

    Above, we bind the click event to the ul whose parent element id is list. The second parameter in the on method is a, which is the real executor of the event. The specific process is as follows:
    → Click a tag
    → Event-based bubbling triggers the ul click Event of a's parent Element
    → The real executor of the event is.

    Event delegation allows us to bind an event to a parent element, which is equivalent to binding an event to all child elements, whether static or dynamically added.

    13. toggle Method

    Multiple events can be executed in sequence. After the last event is executed, the first event is executed.

    $('img[src*=small]').toggle({ function(){}, function(){}, function(){}});

    14. mouseenter and mouseleave Methods

    $(element).mouseenter(function(){}).mouseleave(function(){})

    15. hover Method

    $("p").hover(function(){ $("p").css("background-color","yellow"); },function(){ $("p").css("background-color","pink");});

    I believe this article provides some reference value for jQuery program design.

    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.