JQuery fragment (2) event, jquery fragment event

Source: Internet
Author: User

JQuery fragment (2) event, jquery fragment event

4. Events

● Bind an event to an element using the method name:

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

 

● 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.

 

● Event namespace

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')

 

● 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

 

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

 

● Delete an event

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

 

● 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.

 

● 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 ()

 

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

 

If you want to cancel the registration event.

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

 

● 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 pass in anonymous objects 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.

 

● 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(){
    $("<span>Focused</span>").appendTo("#id").fadeOut(1000);
})
// TriggerHandler
$("#id").click(function(){
$ ("Input"). triggerHandler ("focus"); // does not trigger the default focus action, that is, enter the text box.
})
// Trigger
$("#id").click(function(){
$ ("Input"). trigger ("focus"); // triggers the default and bound behavior of foucs at the same time.
})

 

● Event bubbling and event Delegation

What is event bubbling?

There is such a piece of code.

<!DOCTYPE html>
<body>
    <div>
        <p><a href="#foo"><span>I am a Link!</span></a></p>
        <p><a href="#bar"><b><i>I am another Link!</i></b></a></p>
    </div>
</body>

 

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.

<body>
<div id="container">
    <ul id="list">
        <li><a href="http://domain1.com">Item #1</a></li>
        <li><a href="/local/path/1">Item #2</a></li>
        <li><a href="/local/path/2">Item #3</a></li>
        <li><a href="http://domain4.com">Item #4</a></li>
    </ul>
</div>
</body>

 

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( "<li><a href='http://newdomain.com'>Item #5</a></li>" );

 

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.


● 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(){}
});

 

● Mouseenter and mouseleave Methods

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

 

● Hover Method

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

 

References:
JQuery practice (version 2)
Events and Event Delegation
What does "event bubbling" mean?


How does jquery bind toggle (fun1, fun2) events with bind?

$ ("# Obj"). toggle (fun1, fun2, fun3,...); switches between several functions;

The landlord asked how to use bind binding to stop triggering after repeating the event?
Use unbind ("click") to delete.

This toggle () method can be used directly.
 
How to click jquery and switch between two events

Set a value variable outside click to 0 at first, add 1 after each click trigger, and then let the variable get the remainder of 2. If not, two different states will be obtained, then write the function based on this value.

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.