jquery trigger Event Multi-instance explanation

Source: Internet
Author: User
Tags bind

jquery triggers the event to detach the code

in JS, if we want to trigger a button click event, use the element's OnClick event directly, then call the relevant function, so that the code is combined with HTML, This is not the case in jquery, it has several other ways to make code separate from HTML:

For example, there is a button on the page: <input id= "btn" type= "button" value= "submit"/>

We're going to trigger it. Click events can be in the following two ways:

One: JQuery (function ($) {
$ ("#btn"). Click (function () {alert ("This is the first way to trigger the event")
)

to get the element directly, then call the click Method, and the function writes

Two: JQuery (document) in the event. Ready (function ()
{
$ ("#btn1"). Bind (" Click, function (event) {
Alert ("This is the second way to trigger the event")
})
}  

This method is binding event

Both of the above methods are OK, Where click can be replaced by other events such as Blur,focus

If it is an element to trigger two events, such as loss of focus, get focus, in JS to use the onfocus and onblur events, in jquery directly add to the continuous

The code is as follows Copy Code
$ (function () {
$ ("#txtName"). focus (function () {
$ ("#txtName"). attr ("Value", "");
}). blur (function () {
$ ("#txtName"). AddClass ("AA");
});
})



Or

The code is as follows Copy Code

$ (function () {
$ ("#txtName"). focus (function () {
$ (this). attr ("Value", "");
}). blur (function () {
$ (this). addclass ("AA");
});
})



This represents the current element

Or bind two events using bind can



Triggers an event, or simulates a user action. For example clicks, we can use the code to simulate the user clicks, achieves the effect and the real mouse clicks is the same. In the evolution of the event module I used dispatchevent (standard) and fireevent (IE) to actively trigger events. As follows

The code is as follows Copy Code

...
Dispatch = The consortium?
    function (el, type) {
        try{
             var evt = document.createevent (' Event ');
            evt.initevent (type,true,true);
            el.dispatchevent (EVT);
       }catch (e) {alert (e)};
   }:
    function (el, type) {
        try{
            el.fireevent (' on ' +type);
        }catch (e) {alert (e)}
   };
...
 


jquery does not use the Dispatchevent/fireevent method at all. It uses a different mechanism.

The core method of the JQuery trigger event is JQuery.event.trigger. There are two trigger event methods that it provides to client programmers: Trigger/triggerhandler



The occurrence of an event in some elements can result in two kinds of actions, one is the default behavior, the other is event handler. such as Link a

The code is as follows Copy Code

<a href= "http://mail.sina.com.cn" onclick= "alert (1);" > Sina Email </a>



After clicking, eject 1 (event handler), and click OK to jump (default behavior) to mail.sina.com.cn. Therefore, the design of the function that triggers the event takes into account both of these situations.

 
jquery uses. Trigger and. Triggerhandler to distinguish between:

Trigger performing events hanlder/performing bubbling/performing default behavior
Triggerhandler Execute event handler/do not bubble/do not perform default behavior
 
. Trigger/.triggerhandler's source code is as follows

  code is as follows copy code

Trigger: function (type, data) {
    return This.each (function () {
      & nbsp JQuery.event.trigger (type, data, this);
   });
},
 
triggerhandler:function (type, data) {
    if (This[0]) {
&NBSP;&NBSP;&N bsp;     return JQuery.event.trigger (type, data, This[0], true);
   }
},


As you can see, both call JQuery.event.trigger. One does not pass true when called, and one passes. A triggerhander that passes true means that only the event handler is executed.

Also note the difference: Trigger is an operation on a collection of jquery objects, and Triggerhandler only operates the first element of the jquery object. As follows

The code is as follows Copy Code

<p>p1</p>
<p>p1</p>
<p>p1</p>
<script>
$ (' P '). Click (function () {alert (1)});
$ (' P '). Trigger (' click '); Play 3 times, that is, three P's click is triggered
$ (' P '). Triggerhandler (' click '); Only 1 times, that only triggers the first p click
</script>


Okay, it's time to post the JQuery.event.trigger code.

The code is as follows Copy Code

Trigger:function (event, data, Elem, onlyhandlers) {
Event object or event type
var type = Event.type | | Event
namespaces = [],
Exclusive

......

}



This is the definition of JQuery.event.trigger, which omits most of it. The following list

The code is as follows Copy Code
if (Type.indexof ("!") >= 0) {
Exclusive events trigger only for the exact event (no namespaces)
Type = Type.slice (0,-1);
Exclusive = TRUE;
}



This section is to deal with trigger (' click! ') , which triggers an event that is not a namespace. Variable exclusive is used within jQuery.event.handle after hanging on the event object. As an example

The code is as follows Copy Code

function fn1 () {
Console.log (1)
}
function fn2 () {
Console.log (2)
}
$ (document). Bind (' click.a ', fn1);
$ (document). Bind (' click ', fn2);
$ (document). Trigger (' click! '); 2


Added two click events for document, one with namespace "click.a" and one without "click". Use trigger when the parameter click Add an exclamation mark "!". An event that does not trigger a namespace can be seen from the output of 2. To sum up:

Trigger (' click ') triggers all click events
Trigger (' click.a ') triggers only click events for "CLICK.A"
Trigger (' click! ') Triggering a click event for a non-namespace

Then look.

The code is as follows Copy Code

if (Type.indexof (".") >= 0) {
Namespaced Trigger; Create a regexp to match event type in handle ()
namespaces = Type.split (".");
Type = Namespaces.shift ();
Namespaces.sort ();
}


This paragraph is very well understood, is the processing of trigger (' click.a '), that is, the handling of namespace events.


Then look.

The code is as follows Copy Code

if ((!elem | | jquery.event.customevent[type]) &&!jquery.event.global[type]) {
No jQuery handlers for this event type, and it can ' t have inline handlers
Return
}



For special events such as "GetData" or for events that have been triggered, return directly.

Down

The code is as follows Copy Code

event = typeof Event = = = "Object"?
Jquery.event Object
event[Jquery.expando]? Event:
Object literal
New Jquery.event (Type, Event):
Just the event type (string)
New Jquery.event (type);


There are three kinds of situations

Event itself is an instance of the Jquery.event class
Event is a common JS object (an instance of a Jquery.event class)
Event is a string, such as "click"

Continued

The code is as follows Copy Code

Event.type = type;
Event.exclusive = exclusive;
Event.namespace = Namespaces.join (".");
Event.namespace_re = new RegExp (^|.) + Namespaces.join (". (?:. *.)?") + (. | $)");


Note that Exclusive/namespace/namespace_re is hooked up to the event and can be used in JQuery.event.handle (event namespace).


Down is

The code is as follows Copy Code

Triggerhandler () and global events don ' t bubble or run the default action
if (onlyhandlers | |!elem) {
Event.preventdefault ();
Event.stoppropagation ();
}

Onlyhandlers is only used in Triggerhandler, which does not trigger the default behavior of the element and stops bubbling.



Below is

The code is as follows Copy Code



Handle a global Trigger


if (!elem) {


Todo:stop taunting the data cache; Remove global events and always attach to document


Jquery.each (Jquery.cache, function () {


Internalkey variable is just used to make it easier to find


And potentially change this stuff later; Currently it just


Points to Jquery.expando


var Internalkey = Jquery.expando,


Internalcache = this[Internalkey];


if (Internalcache &amp;&amp; internalcache.events &amp;&amp; internalcache.events[type]) {


JQuery.event.trigger (event, data, InternalCache.handle.elem);


}


});


Return


}



Here is a recursive call. If there is no elem element, then take it from the Jquery.cache.



Followed by

The code is as follows Copy Code

Don ' t does events on text and comment nodes
if (Elem.nodetype = = 3 | | elem.nodetype = = 8) {
Return
}


property, the text node returns directly.



Below is

The code is as follows Copy Code

Clone any incoming data and prepend the event, creating the handler arg list
data = Data!= null? Jquery.makearray (data): [];
Data.unshift (event);


First, the argument data is placed in the array, and the event object is placed in the first position of the array.


Followed by

The code is as follows Copy Code



Fire event on the current element, then bubble up the DOM tree


do {


var handle = Jquery._data (cur, "handle");





Event.currenttarget = cur;


if (handle) {


Handle.apply (cur, data);


}





Trigger an inline bound script


if (Ontype &amp;&amp; jquery.acceptdata (cur) &amp;&amp; cur[ontype] &amp;&amp; cur[ontype].apply (cur, data) = = F Alse) {


Event.result = false;


Event.preventdefault ();


}





Bubble up to document, then to window


Cur = Cur.parentnode | | cur.ownerdocument | | Cur = = event.target.ownerDocument &amp;&amp; window;


while (cur &amp;&amp;!event.ispropagationstopped ());



This piece of code is important and does the following things

Take handle
Perform
Perform events added by onxxx (such as onclick= "Fun ()")
Take the parent element
The while loop repeats these four steps repeatedly to simulate event bubbling. Until the Window object

Next up is

The code is as follows Copy Code



If Nobody prevented the default action, do it now


if (!event.isdefaultprevented ()) {


var old,


Special = jquery.event.special[Type] | | {};





if (!special._default | | special._default.call (elem.ownerdocument, event) = = False) &amp;&amp;


! (Type = = "click" &amp;&amp; jquery.nodename (Elem, "a")) &amp;&amp; Jquery.acceptdata (elem)) {





Call a native DOM method on the target with the same name as the event.


Can ' t use a. isfunction () Check here because IE6/7 fails that test.


Ie&lt;9 dies to hidden Element (#1486), may want to revisit a try/catch.


try {


if (Ontype &amp;&amp; elem[type]) {


Don ' t Re-trigger an OnFoo event, we call it FOO () method


Old = elem[Ontype];





if (old) {


elem[Ontype] = null;


}





jQuery.event.triggered = type;


elem[type] ();


}


\ catch (ieerror) {}





if (old) {


elem[Ontype] = old;


}





jQuery.event.triggered = undefined;


}


}


This section is a trigger for the browser default behavior. such as Form.submit (), Button.Click () and so on.

Note that because of the security restrictions on links in Firefox, jquery's default behavior for linking is uniformly designed to not trigger. That is, you cannot make a link jump by trigger ().





Jquery Monitor Key, enter the trigger event instance

code example:

  code is as follows copy code

< The script type= "Text/javascript"
$ (function () {
$ (' Input:text:first '). focus ();//Concentrate on the first text box
var $inp = $ ( ' Input '); All input elements
$inp. KeyPress (function (e) {//here gives the function an event parameter named E, called event also line, Random, E is the event that IE window occurs.
    var key = E.which//e.which is the key value
    if (key = = {
&NBSP;&NBSP;&NBSP;&N) bsp;    alert ("AAA");
   }
});

});

The


drags a login control and then converts it to template for custom development.


The return key of the text bar is captured in the above code, which triggers the Loginbutton to submit the login information for verification, but uses $ ("[Id$=loginbutton]"). Click (), only valid on Firefox, In IE invalid, fluke try $ ("[Id$=loginbutton]"). focus (), in IE, effective, on IE, focusing () that is completed the focal point and then performed the click, this is why?

The code is as follows Copy Code

$inp. KeyPress (function (event) {
var key = Event.which;
if (key = = 13) {
$ ("[Id$=loginbutton]"). Click (); Support Firefox,ie Wu School
$ (' input:last '). focus ();
$ ("[Id$=loginbutton]"). focus (); Invalid support Ie,firefox.

The above two implementations both support IE and Firefox
}
});

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.