Learn jquery from scratch (v) jquery event and event object _jquery

Source: Internet
Author: User
Tags anonymous documentation html tags

I. Summary

Events are the soul of scripted programming. So this chapter is also the focus of jquery learning. This article provides a detailed explanation of event handling and event objects in jquery.

Two. Foreword

This article is one of the most important articles in this series so far, and it is significant enough to be seen. It is reflected that more examples are enumerated. I'll enumerate the examples as much as time allows. The actual use of the production of the example can not be added to the article for the time being, but perhaps finally I will enumerate some works for reference. In addition my level is limited, because I am not a UI designer. The article may have the wrong place, hope everybody helps to point out, together study progresses together. In a world of technology, we have no interest whatsoever. I hope we all hold each other to encourage the mentality of the reply to the radical comments I will also consider, but hope to be able to respect each other, protect the blog park this piece of the programmer's Pure Land!

Three. Event and Event objects

Used to be in my JavaScript Common Script Library series (ii): Methods for adding event multicast delegates and JavaScript Common Script Library series (iii): Formatting event Objects/Event object Details "the events and event objects in JavaScript have been explained in two articles.

First look at the ways in which you add events that we often use:

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head&gt; &lt;Title&gt;Events in JavaScript&lt;/Title&gt; &lt;Script Type= "Text/javascript" Src= "Scripts/jquery-1.3.2-vsdoc2.js"&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (function() {document.getElementById ("TestDiv2"). onclick = showmsg; })functionShowMsg (Event) {alert ("!!!"); }&lt;/Script&gt; &lt;/Head&gt; &lt;Body&gt; &lt;Div Id= "TestDiv1" OnClick= "showmsg ();"&gt;Click event 1&lt;/Div&gt; &lt;Div Id= "TestDiv2"> Click event 2</div> </body> html>


We most often add events by adding onclick element attributes to elements.

The way to add an onclick event for TestDiv2 is to modify the DOM properties.

In the previous chapter, we explained what an element attribute is and what is a DOM property. The two methods have the same effect. A prompt box appears when you click a div.

Note that although the effect is the same, it is not equivalent.

document.getElementById ("TestDiv2"). onclick = showmsg;


is equivalent to:

<div =" alert ("!!! > click the event 1</div>  


Notice the difference between the two? The way we often modify element attributes to add events is actually to create an anonymous function:

document.getElementById (function (event) {alert ("!!!");  


The signature of this anonymous function is the same as our handwritten showmsg signature, so we can assign the showmsg directly to the onclick.

The drawbacks of this approach are:

1. Only one event handler function can be bound for one event. Using the ' = ' assignment will flush out all the event handlers that were previously bound for this time.

2. The way to get event objects in an event function, whether it is an anonymous function or a bound function, is handled differently in different browsers:

In IE, the event object is a property of the Window object. The event handler must access the event object like this:

obj.onclick=function () 
{ 
var oevent = window.  Event }

In the DOM standard, an event object must be passed as a unique parameter to the event handler function:

obj.onclick=function () 
{ 
var oevent = arguments[0];} 

In addition to using argument[0] to access this parameter, we can also specify the parameter name, which is equivalent to the following code:

obj.onclick=function (oevent) 
{ 
}

Browsers that are currently compatible with DOM have firefox,safari,opera,ie7 and so on.

3. Functions that add multicast delegates are not the same in different browsers.

The following is a method for adding multicast delegates in the "JavaScript Common Script Library series (ii): Adding Event Multicast Delegates" article:

Unified method of adding multicast event delegates to an object 
/* Parameter description: Otarget: The object to which to add the event. such as "document". Seventtype: Event type. For example, click event "click".  Fnhandler: The method that is invoked when an event occurs. For example, a static function "Hidecalendar"   var CF = document.getElementById ("Calframe");  if (cf!= null && hidecalendar!= null)  Scripthelper.addeven Tlistener (document, "click", Hidecalendar); */ScriptHelper.prototype.addEventListener = function ( Otarget, Seventtype, Fnhandler) {if (otarget.addeventlistener) //for dom { Otarget.addeventlistener (Seventtype, Fnhandler, false)} else if (otarget.attachevent) //for ie {otarget.attachevent ( "on" + Seventtype, Fnhandler); } } 


So we should first abandon <div onclick= "..." ></div> the way to add events by modifying element attributes. Try to bind multiple event handlers for an event by adding multicast event delegates, such as adding a method to close the pop-up layer for a Document object's Click event, and using multicast does not affect the original event handler function of the Document object.

Four. Events in jquery

With jquery, we have a series of functions that handle object events.  The basics are still understood, but you don't have to implement the function of handling multicast event delegates. There is the so-called jquery, drink tea every day water. Here are some examples of the bind () method that is most commonly used in jquery:

$ ("#testDiv4"). Bind ("click", ShowMsg); 


We add the event handler function showmsg for the column click event for the element that ID is testDiv4.

Benefits of using the JQuery event handler function:

1. A multicast event delegate is added. That is, adding a method for the Click event does not overwrite the original event handler for the object's Click event.

$ ("#testDiv4"). Bind (function (event) {alert ("one");}; $ ("#testDiv4"). Bind (function (  Event) {alert ("two");});       


When you click the TestDiv4 object, you are prompted "one" and "two" in turn.

2. Unified the event name.
When you add a multicast event delegate, the event name in IE is preceded by "on". But using the bind () function we don't have to distinguish between IE and DOM, because internal jquery has helped us unify the name of the event.

3. You can control the object's behavior in all scripts.
Let the HTML code section notice only the "show" logic. The trend now is to cut the behavior, content and style of the HTML cleanly. It uses script to control element behavior, control element content with HTML tag, control element style with CSS. You can avoid adding events directly to HTML tags by using the jquery event handler function.

The following is the underlying jquery event handler function:

Event handler handling:

Name Description Example

Bind (type, [data], FN)

Bind an event handler function to a specific event (like click) for each matching element. When each paragraph is clicked, the text pops up:

$ ("P"). Bind ("click", Function () {
Alert ($ (this). text ());
});

One (type, [data], FN) Bind a one-time event handler for each matching element's specific event (like click). When all the paragraphs are clicked for the first time, display all their text:

$ ("P"). One ("click", Function () {
Alert ($ (this). text ());
});

Trigger (event, [data]) Triggers a class of events on each matching element.

This function also causes the default behavior of the browser to be executed with the same name. For example, if you use trigger () to trigger a ' submit ', the same will cause the browser to submit the form. If you want to block this default behavior, you should return false.

You can also trigger the custom event registered by bind ()

To pass an argument to an event:

$ ("P"). Click (Function (event, a, b) {
An ordinary click event, A and B are undefined types
If triggered with the following statement, then a points to "Foo" and B points to "bar".
}). Trigger ("click", ["foo", "Bar"]);

Triggerhandler (event, [data]) does not perform browser default actions.

$ ("#old"). Click (function () {
  $ ("input"). Trigger ("focus");
});
$ ("#new"). Click (function () {
  $ ("input"). Triggerhandler ("Focus");
});
$ ("input"). focus (function () {   $ (' <span>Focused!</span> '). Appendto ("Body"). Fadeout ( 1000); });

Unbind (Type, fn) A reverse operation of BIND (), which deletes the bound event from each matching element.

If there are no parameters, all bound events are deleted.

You can unbind the custom event you registered with BIND ().

If the event type is provided as a parameter, only the binding event of that type is deleted.

If the handler function passed at binding is used as the second argument, only this particular event handler is deleted.

Unbind all events from all paragraphs:
$ ("P"). Unbind ()

Unbind the Click event of a paragraph:
$ ("P"). Unbind ("click")

Deletes the binding of a particular function, passing the function as a second argument:

var foo = function () {
Code to handle an event
};
$ ("P"). Bind ("click", foo); // ... When you click on the paragraph, it triggers Foo
$ ("P"). Unbind ("click", foo); // ... Will never be triggered Foo


Five. Examples of common event functions

1.bind (type, [data], FN) function Example

Bind () is the most commonly used function, note the data parameter on the method signature, and you can pass some additional data before the event is processed:

function handler (event) {alert (Event.data.foo);} $ ("P"). Bind (    


Note the use of the event parameter. The event object is unified in jquery, and the event object is passed as the unique parameter of the event handler function.

The data parameters are also accessed through Event.data. Why do I have to supply the data parameter?

Because we often have this problem: you want special handling in event processing based on some data from the source of the event.

At present there are two kinds of dispute resolution methods on the Internet:

(1) Use custom element attributes to store data.

Like what:

<IDCustomer= "Customer Data 1"> Get Custom Data-1</div>   



To get the data in the event handler function:

$ ("#testDiv5"). Bind (function (event) {alert ($ (event.target). attr ("Customer"))   ; 


The attr function is the knowledge in the previous lecture, which is used to get the element attributes of the elements, and to get the custom element properties. When you click the Div, it appears:

(2) using a script to pass data to an event handler function:

<id= "testDiv6"> Get Custom Data-2</div>     

The


element does not have any custom properties, and additional data is passed when the event handler is added:

$ ( "#testDiv6"). Bind ( "click", {customer:  "Customer Data 2"}, function (event) {alert ( event.data.customer)});       


Click the div after the results and Method 1 the same:

Method 1 makes it easy to store and find data. However, custom properties are validated by the non-domain.

Method 2 You have to find ways to store your data, and you need to make rules to find the data for the specified element.

Approach 1 from the developer perspective is simpler and more intuitive. But the disadvantages are rather serious. So how to make a choice for everyone to decide.

One (type, [data], FN) function is the same as bind, but only once.

2. trigger (event, [data]) and Triggerhandler (event, [data])

Although some events are bound for an element, such as click, but sometimes you want to trigger these events in your program, these two functions can implement this functionality.

The main difference is that trigger will start the browser default action, and Triggerhandler will not start.

These two functions are clearly distinguished by the following example:

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head&gt; &lt;Title&gt;jquery event handling: Trigger and Triggerhandler examples&lt;/Title&gt; &lt;Script Type= "Text/javascript" Src= "Scripts/jquery-1.3.2-vsdoc2.js"&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (function() { $("#old"). Click (function() { $("#divResult"). HTML (""); $("Input"). Trigger ("Focus"); }); $("#new"). Click (function() { $("#divResult"). HTML (""); $("Input"). Triggerhandler ("Focus"); }); $("Input"). Focus (function() { $("&lt;span&gt;Focused!&lt;/span&gt;"). Appendto ("#divResult"); }); })&lt;/Script&gt; &lt;/Head&gt; &lt;Body&gt; &lt;button Id= "old"&gt;. Trigger ("Focus")&lt;/button&gt; &lt;button id= "new" >. Triggerhandler ("Focus") </button><BR /> <br /> <input type= "text" value= "to be focused" /> <div id= "Divresult" ></ div> > </html>     



When you click the ". Trigger" button, the focesed is called two times, and the input element gets the focus:

When you click the. Triggerhandler button, you call only once, and the input element does not have the focus:

That is, the trigger function sets out the browser's default to get focus behavior, so that the input element gets the focus, so it calls the focused event handler again.

Triggerhandler only invokes event handlers that are bound for the focus event, but does not raise browser behavior, so the last INPUT element does not have the focal point.

Six. Shortcut event Helpers

Bug Tip: Jquery-1.3.2-vsdoc2.js This latest official class library with smart tips, you can't use shortcut events, such as Click (), focus (). There is no problem using a different version of the class library.

Although we can use event handlers to do almost all of the object's events, jquery provides encapsulation of common events. For example, click the two methods that correspond to the event, click (), and click (FN) to trigger the clicked event and set the Click event respectively.

To set the Click event:

$ ("#testDiv"). Click (function (event) {alert ("Test div clicked!");   


is equivalent to:

$ ("#testDiv"). Bind (function (event) {alert ("Test div clicked!");   

Trigger Click event:

$ ("#testDiv"). Click ();


is equivalent to

$ ("#testDiv"). Trigger ("click"); 

Note that this is equivalent to trigger rather than triggerhandler.

This kind of method in jquery in English is called the event Helpers, I cannot find the very good translation way, therefore according to the function called it "the Quick Method", the collection good translation name!

The following is a list of the shortcut methods for jquery:

Since all are the corresponding events, so no longer write the description and examples.

Name Description Example
Blur ()
Blur (FN)
Change ()
Change (FN)
Click ()
Click (FN)
DblClick ()
DblClick (FN)
Error ()
Error (FN)
Focus ()
Focus (FN)
KeyDown ()
KeyDown (FN)
KeyPress ()
KeyPress (FN)
KeyUp ()
KeyUp (FN)
Load (FN)
MouseDown (FN)
MouseEnter (FN)
MouseLeave (FN)
MouseMove (FN)
Mouseout (FN)
MouseOver (FN)
MouseUp (FN)
Resize (FN)
Scroll (FN)
Select ()
Select (FN)
Submit ()
Submit (FN)
Unload (FN)

Seven. Interactive Help method

In addition to basic practice, jquery provides two and event-related help methods: hover (over, out) and toggle (FN, fn2, Fn3,fn4,...)

1. hover (over, out)

The hover function mainly solves the problem of mouseover and mouseout functions in primitive JavaScript, and look at the following example:

There are two div (red area), which has nested a div (yellow area). The HTML code is as follows:

 &lt;Div Class= "outer" Id= "Outer1"&gt;Outer 1&lt;Div Class= "inner" Id= "Inner1"&gt;Inner 1&lt;/Div> </div> <div class= "outer" id= "Outer2" > Outer 2 <div class= "inner" id= " Inner2 "</div> </div> "<div Span class= "attr" >id= "console" ></div >                

Bind to the following events:

 <script type = "Text/javascript" > "function" event) {$ ( ' #console '). Append ( ' <div> ' +event.type+  ' </div> '); } $ (function () {$ ( ' #outer1 '). Bind ( ' mouseover ', the). Bind ( ' mouseout ', a); $ ( ' #outer2 '). Hover (report,report);}); </script>        


Outer1 we used the mouseover and mouseout events, and when the mouse moved from the red area of Outer1 to the yellow area, it found that although it was moving inside the outer1, it triggered the Mouseout event:

Most of the time we do not want the results of the above image, but we want only the mouse to move inside the Outer1 does not trigger the event, Outer2 use the hover () function to achieve this effect:

Note that the event name here goes into "MouseEnter", leaving the term "mouseleave" instead of "mouseover" and "MouseLeave" events.

Experienced developers will immediately think of the creation of pop-up menus, often encountered this problem: the pop-up menu set the Mouseout event automatically shut down, but the mouse in the pop-up menu moves often inexplicably trigger the Mouseout event to shut down the menu. The hover () function helps us to solve the problem well.

2. Toggle (FN, fn2, Fn3,fn4,...)

The toggle function can add the Click event binding function for an object, but sets the call function sequentially after each click.

If a matching element is clicked, the first specified function is triggered, and when the same element is clicked again, the specified second function is triggered, and if there are more functions, it is triggered again until the last one. Successive calls to these functions are repeated for each subsequent click.

You can use Unbind ("click") to delete.

The following example shows how to use the Toggle function:

&lt;!DOCTYPE Html Public "-//w3c//dtd HTML 4.01//en" "Http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;Html&gt; &lt;Head&gt; &lt;Title&gt;Toggle Example&lt;/Title&gt; &lt;Link Rel= "stylesheet" Type= "Text/css" Href= "Css/hover.css"&gt; &lt;Script Type= "Text/javascript" Src= "Scripts/jquery-1.3.2-vsdoc2.js"&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (function() { $("Li"). Toggle (function() { $(This). CSS ({"List-style-type":"Disc","Color":"Blue"}); },function() { $(This). CSS ({"List-style-type":"Square","Color":"Red"}); },function() { $(This). CSS ({"List-style-type":"None", "color": </script> head> > <ul> "li style= "Cursor:pointer" > Click Me</li> ul> </body</html>       


The result is a single click "Click Me" to transform the list symbol and the text color once.


Eight. Using the JQuery Event object

Event objects are naturally unavoidable with events. Because of the differences in the acquisition of event objects between different browsers and the properties of event objects, it is difficult to use event objects across browsers.

The event object is unified in jquery, and when the event handler is bound, the jquery-formatted event object is passed in as a unique parameter:

$ ("#testDiv"). Bind (function (event) {});  


For a detailed description of the Event object, you can refer to the jquery official documentation: Http://docs.jquery.com/Events/jQuery.Event

The jquery event object merges the differences in different browsers, such as the Event.target property in all browsers to get the trigger of the event (using the native event object in IE, access to event.srcelement).

The following are the properties that the jquery event object can support in expanding browsers:

Property name Describe Example

Type

Event type. If you use an event handler to handle multiple events, you can use this property to get the event type, such as Click.
$ ("a"). Click (Function (event) { 
alert (event.type); 
});

Target

Get Event Trigger DOM object
$ ("a[href=http://google.com]"). Click (Function (event) { 
alert (event.target.href); 
});

Data

An additional parameter is passed in when the event is called.
$ ("a"). each (the function (i) { 
$ (this). bind (' click ', {index:i}, function (e) { 
alert (' Me index is ' + E.data.index); c2/>}); 

Relatedtarget

For mouse events, mark the DOM element that was left or entered when the event was triggered
$ ("a"). Mouseout (function (event) { 
alert (event.relatedtarget); 
});

Currenttarget

The DOM object of the current triggering event before bubbling, equivalent to this.
$ ("P"). Click (Function (event) { 
alert (event.currentTarget.nodeName); 
});

Result: P

pagex/y

In mouse events, the horizontal/vertical coordinates of the event relative to the origin of the page.
$ ("a"). Click (Function (event) { 
alert ("Current mouse position: + Event.pagex +," + Event.pagey); 
});

Result

The value returned by the previous event handler function
$ ("P"). Click (Function (event) {return 
"Hey" 
}); 
$ ("P"). Click (Function (event) { 
alert (event.result); 
});

Result: "Hey"

TimeStamp

The time stamp at which the event occurred.
var last; 
$ ("P"). Click (Function (event) { 
if (last) 
alert (' time since last event ' + event.timestamp-last); 
last = Event.timestamp; 
});

This is the property of the event object provided in the official jquery documentation. In the "jquery Combat" book also provides the following browser-supported properties, time relationship I didn't try every attribute, you can help verify that you are available in all browsers:

Property name Describe Example
Altkey Whether the ALT key is pressed. Press RETURN True
Ctrlkey CTRL key is pressed, press return True
Metakey Returns true if the META key is pressed.
The META key is the CTRL key for the PC machine, or the command key on the Mac machine.
Shiftkey If the SHIFT key is pressed, press return True
KeyCode Returns the pressed key for the KeyUp and KeyDown events. Case-insensitive, both a and a return 65.

Use the which property for the KeyPress event, because the which property is still reliable across browsing.
which For keyboard events, returns the numeric encoding of the key that triggered the event. For mouse events, return the mouse button number (1 left, 2, 3 right).
screenx/y For mouse events, gets the horizontal/vertical coordinates of the event relative to the screen origin

Event objects also have events in addition to owning attributes. There are some things that are certain to be used, such as canceling bubbling Stoppropagation (), and so on. The following is a list of functions for the jquery event object:

Name Description Example

Preventdefault ()

Cancels events that may cause any semantic action. For example, the <a> element's href link loading, the form submission, and click to cause the check box to toggle state.
$ ("a"). Click (Function (event) { 
event.preventdefault (); 
Do something 
});

Isdefaultprevented ()

Have you invoked

Preventdefault ()

Method
$ ("a"). Click (Function (event) { 
alert (event.isdefaultprevented ()); 
Event.preventdefault (); 
Alert (event.isdefaultprevented ()); 
});

Stoppropagation ()

Cancel Event Bubbling
$ ("P"). Click (Function (event) { 
event.stoppropagation (); 
Do something 
});

Ispropagationstopped ()

Have you invoked

Stoppropagation ()

Method
$ ("P"). Click (Function (event) { 
alert (event.ispropagationstopped ()); 
Event.stoppropagation (); 
Alert (event.ispropagationstopped ()); 
});

Stopimmediatepropagation ()

Cancels the execution of other event-handling functions and suppresses event bubbling.

If the same event binds multiple event-handler functions, calling this method in one of the event-handler functions will not continue to invoke the other event-handler function.
$ ("P"). Click (Function (event) { 
event.stopimmediatepropagation (); 
}); 
$ ("P"). Click (Function (event) { 
//This function won ' t is executed 
});

Isimmediatepropagationstopped ()

Have you invoked

Stopimmediatepropagation ()

Method
$ ("P"). Click (Function (event) { 
alert (event.isimmediatepropagationstopped ()); 
Event.stopimmediatepropagation (); 
Alert (event.isimmediatepropagationstopped ()); 
});


The Stoppropagation () in these functions are the most important functions that we use and are definitely used. The equivalent of manipulating the original event object's Event.cancelbubble=true to cancel bubbling.

Nine. Summary

Event is the soul of JavaScript, and it took me a long time to write this article to translate the official jquery API documentation. The list of many examples directly from the official web excerpt, some of the list of methods I have not used, so if you find the problem, please notify me to revise.

The next article will explain the Ajax and animation effects respectively. Finally, learn about jquery's plug-in development by explaining two of my modified jquery plug-ins.
Author: Zhang Zixiu
Source: http://www.cnblogs.com/zhangziqiu/

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.