JQuery is a JavaScript library that helps simplify JavaScript™ and asynchronous JavaScript + XML (Ajax) programming. Unlike a JavaScript library like this, JQuery has a unique rationale for succinctly representing Common, complex code. Learn the basics of JQuery, explore its features and capabilities, perform some common Ajax tasks, and master how to extend JQuery with Plug-ins.
--> --> -->
What is JQuery?
JQuery was created by John Resig in early 2006 and is a useful JavaScript library for any programmer using JavaScript code. Whether you're just in touch with the JavaScript language, and want to get a library that solves some of the complex problems in the Document Object Model (model,dom) script and Ajax development, or as a tired DOM script and Ajax JQuery will be your first choice as a veteran JavaScript expert in the tedious repetitive work of development.
JQuery can help you keep your code simple and readable. You no longer have to write large stacks of repetitive loops and DOM script library calls. With JQuery, you can grasp the main points of the problem and implement the functionality you want with the least amount of code possible.
There is no doubt that the principle of jQuery is unique: Its purpose is to ensure that the code is concise and reusable. Once you understand this principle, you can start learning this tutorial and see how much jQuery has improved our programming style.
|
Back to the top of the page |
|
Some simple code simplification
The following is a simple example that illustrates the impact of JQuery on your code. To perform some really simple and common tasks, such as attaching a click event to each link in one area of a page, you can use pure JavaScript code and a DOM script, as shown in Listing 1 .
Listing 1. DOM scripts that do not use JQuery
var external_links = document.getElementById (' external_links ');
var links = external_links.getelementsbytagname (' a ');
for (Var i=0;i < links.length;i++) {
var link = links.item (i);
Link.onclick = function () {return
confirm (' Your are going to visit: ' + This.href ');}
|
Listing 2 shows the same functionality that was implemented using JQuery.
Listing 2. DOM script with JQuery
$ (' #external_links a '). Click (function () {return
confirm (' Your are going to visit: ' + this.href);
}); |
Isn't it amazing? With JQuery, you can grasp the main points of the problem and just let the code implement the functionality you want, eliminating some tedious process. You do not have to loop through the elements, and theclick()function completes these operations. There is also no need for multiple DOM script calls. You only need to use a short string to define the elements that you want.
Understanding how this code works can be a bit tricky. First, we use the$()most powerful function in the function--jquery. Typically, we use this function to select elements from a document. In this case, a string containing some cascading style sheets (cascading style sheet,css) syntax is passed to the function, and jQuery can find the elements as efficiently as possible.
If you have a basic knowledge of CSS selectors, you should be familiar with these syntaxes. In Listing 2 , the#external_linkselement that is used to retrieveidexternal_linksthe.aThe following space indicates that JQuery needs to retrieveexternal_linksall elements in the element<a>. Speaking in English is very round the mouth, even in the DOM script, but in the CSS this is simple
$()function returns a JQuery object that contains all the elements that match the CSS selector. The jquery object is similar to an array, but it comes with a large number of special jquery functions. For example, you canclickassign the click handler function to all the elements in the JQuery object by calling the function.
You can also$()pass an element or an array of elements to a function that encapsulates the elements in a JQuery object. You might want to use the JQuery function for some objects, such as objects, using this featurewindow. For example, we typically assign functions to load events as follows:
Window.onload = function () {//do-stuff when the page was done
loading
}; |
Code with the same functionality written in JQuery:
$ (window). Load (function () {
//Run this is when the whole page has been downloaded
}); |
As you may realize, waiting for the window to load is very slow and painful, because you have to wait for the entire page to load all the content, including all the pictures on the page. Sometimes, you want to finish loading the picture first, but in most cases you just load the Hypertext Markup Language (hypertext Markup language,html). JQuery solves this problem by creating special events in the documentready, as follows:
$ (document). Ready (function () {//do this stuff when the HTML was all
ready
}); |
This codedocumentcreates a JQuery object around the element, and then builds a function to invoke the instance when the HTML DOM document is ready. You can call this function arbitrarily, as needed. And be able to call this function using shortcuts in real jQuery format. This is simple, just$()passing a function to the function is OK:
$ (function () {
//Run this when the HTML was done downloading
}); |
So far, I've introduced$()three uses of the function. The fourth method can use strings to create elements. The result produces a JQuery object that contains the element. The example shown in Listing 3 adds a paragraph to the page.
Listing 3. Create and attach a simple paragraph
$ (' <p></p> ')
. html (' Hey world! ')
. CSS (' background ', ' yellow ')
. Appendto ("body"); |
As you may have noticed in the previous example, another powerful feature in JQuery is the method link (methods chaining). Each time a method is invoked on a jquery object, the method returns the same jquery object. This means that if you need to call multiple methods on a JQuery object, you do this without having to retype the selector: making Ajax Simple
$ (' #message '). CSS (' background ', ' yellow '). html (' hello! '). Show (); |
|
Back to the top of the page |
|
Using JQuery will make Ajax as simple as it gets. JQuery provides a number of functions that make simple work easier, and complex work becomes less complex.
The most common use of Ajax is to load a piece of HTML code into an area of the page. To do this, simply select the element you want, and then use theload()function. The following is an example for updating statistics:
$ (' #stats '). Load (' stats.html '); |
Typically, we simply pass some parameters to a page in the server. As you would expect, using JQuery to do this is a very simple operation. You can use$.post()or$.get(), this is determined by the method you want. You can also pass an optional data object and callback function, if needed. Listing 4 shows a simple example of sending data and using callbacks.
Listing 4. Using Ajax to send data to a page
$.post (' save.cgi ', {
text: ' My string ',
number:23
}, function () {
alert (' Your data has been. ');
}); |
If you do need to write some complex Ajax scripts, you need to use a$.ajax()function. You can specifyxml,scripthtmlorjson, JQuery will automatically prepare the appropriate results for the callback function so that you can use the result immediately. You can also specifybeforeSend,error,,successorcompletecallback functions to provide users with more feedback about the Ajax experience. In addition, there are other parameters available that you can use to set the timeout for the Ajax request, or to set the status of the page "last modified." Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.
Listing 5 $.ajax () makes Ajax simpler by complexity
$.ajax ({
URL: ' document.xml ',
type: ' Get ',
dataType: ' xml ',
timeout:1000,
error:function () {
alert (' Error loading XML document ');
},
success:function (XML) {
//do something with XML
}
}); |
When the success callback function returns an XML document, you can use JQuery to retrieve the XML document in the same way that it retrieves an HTML document. This makes processing XML documents quite easy, and integrates content and data into your Web site. Listing 6 showssuccessan extension of the function that<item>adds a list item to the Web page for each element in the XML.
listing 6. Using JQuery to process XML documents
Success:function (XML) {
$ (XML). Find (' item '). each (function () {
var item_text = $ (). text ();
$ (' <li></li> ')
. HTML (item_text)
. Appendto (' ol ');
}
|
|
Back to the top of the page |
|
Add animations to HTML
You can use JQuery to handle basic animations and display effects.animate()A function is the core of an animated code that changes the CSS style values of any numeric value that changes over time. For example, you can change height, width, opacity, and position. You can also specify the speed of the animation, either as a millisecond or as a predefined speed: slow, medium, or fast.
Here is an example of changing the height and width of an element at the same time. Note that these parameters do not have a start value, only the final value. The start value is taken from the current dimension of the element. I also attached a callback function.
$ (' #grow '). Animate ({height:500, width:500}, "Slow", function () {
alert (' The element is done growing! ');
}); |
The built-in functions of jQuery make it easier to do more common animations. You can useshow()and element to displayhide()immediately or at a specific speed. You can also usefadeIn()andfadeOut(), or,slideDown()andslideUp()Show and hide elements, depending on the display effect you need. The following example defines a sliding navigation menu.
$ (' #nav '). Slidedown (' slow '); |
|
Back to the top of the page |
|
DOM Scripting and event handling
Perhaps JQuery is best at simplifying DOM scripting and event handling. Traversing and processing the DOM is simple, while attaching, removing, and invoking events is also easy, and not as error-prone as manual operations.
In essence, jQuery can make common operations in DOM scripts easier. You can create elements and useappend()functions to link them with other elements, useclone()copy elements, usehtml()settings, delete content using functions,empty()Delete all elements using functions,remove()even with functions, and usewrap()other elements to Some elements to wrap up.
By traversing the DOM, some functions can be used to change the contents of the JQuery object itself. Can get all of the elementssiblings(),parents()andchildren(). You can also selectnext()andprev()sibling elements.find()a function is perhaps the most powerful function that allows you to use the jquery selector to search for descendant elements of elements in a jquery object.
If you useend()functions together, these functions will become more powerful. This function is similar to the Undo function, which is used to return tofind()parents()the JQuery object before the call or function (or other traversal function).
If used together with method chaining, these functions can make complex operations look very simple. Listing 7 shows an example that contains a login form and handles some of the elements associated with it.
listing 7. Easily traverse and process DOM
$ (' form#login ')
//Hide all of the labels inside the form with the ' optional ' class
. Find (' label.optional '). Hide (). E nd ()
//Add a red border to any password fields in the form
. Find (' Input:password '). CSS (' border ', ' 1px solid red ') . End ()
//Add a submit handler to the form
. Submit (function () {return
confirm (' Are for your sure you want to submit ?');
}); |
Whether you believe it or not, this example is just a line of linked code that is full of blank. First, select the login form. It then discovers that it contains optional tags, hides them, and invokes theend()returned form. Then I created the password field, changed its bounds to red, and called back to theend()form again. Finally, I added a Submit event handler to the form. What's particularly interesting is that, in addition to its simplicity, JQuery optimizes all query operations, making sure that everything is well linked, without having to perform two queries on one element.
Handling common events is as simple as calling a function (click()for example,submit()ormouseover()) and passing an event handler function for it. In addition, you can usebind('eventname', function(){})the specified custom event handlers. You can use tounbind('eventname')delete certain events or use tounbind()Delete all events. For a complete list of how these functions are used, see the JQuery Application Programming Interface (application program INTERFACE,API) documentation in resources .
|
Back to the top of the page |
|
Release the powerful power of the JQuery selector
We often use IDs to select elements, for example#myid, or through class names, such asdiv.myclassto select elements. However, JQuery provides a more complex and complete selector syntax, allowing us to select almost all element combinations in a single selector.
JQuery's selector syntax is primarily based on CSS3 and XPath. The more you know about CSS3 and XPath, the more handy it is to use jQuery. For a complete list of JQuery selectors, including CSS and XPath, see the links in resources .
CSS3 contains some syntax that is not supported by all browsers, so we rarely use it. However, we can still use CSS3 to select elements in jquery because jquery has its own custom selector engine. For example, to add a horizontal bar to each empty column in a table, you can use::emptypseudo-selector (pseudo-selector):
$ (' Td:empty '). html ('-'); |
What if you need to find all elements that do not contain a particular class? CSS3 also provides a syntax to do this, using a:notpseudo selector: The following code shows how to hide allrequiredinput without a class:
$ (' Input:not (. required) '). Hide (); |
As in CSS, you can use commas to connect multiple selectors into one. The following is a simple example of hiding all types of lists on a page at the same time:
$ (' UL, OL, DL '). Hide (); |
XPath is a powerful syntax for searching for elements in a document. It is slightly different from CSS, but it can achieve slightly more functionality than CSS. To add a border to the parent element of all check boxes, you can use the/..syntax of XPath:
$ ("input:checkbox/."). CSS (' border ', ' 1px solid #777 '); |
JQuery also adds a few selectors that are not in CSS or XPath. For example, to make a table more readable, it is often possible to attach a different class name to the odd or even rows of a table--or to fragment a table (striping). Using jQuery effortlessly can do this, thanks to theoddpseudo selector. The following example uses astripedclass to change the background color of all odd rows in a table:
$ (' table.striped > Tr:odd '). CSS (' background ', ' #999999 '); |
We can see how the powerful jQuery selector simplifies the code. Whatever elements you want to deal with, regardless of whether the element is concrete or fuzzy, it is possible to find a way to define them using a jquery selector.
|
Back to the top of the page |
|
Using Plug-ins to extend JQuery
Unlike most software, using a complex API to write Plug-ins for jQuery is not very difficult. In fact, the JQuery plug-in is very easy to write, and you even want to write some plug-ins to make the code simpler. Here are some of the most basic jQuery plug-ins you can write:
$.fn.donothing = function () {return this
;
}; |
Although very simple, but still need to do some explanation of this plugin. First, if you want to add a function to each JQuery object, you must assign the function to$.fn. Second, the function must return athis(JQuery object) so that it does not interrupt the method chaining.
You can easily build on top of this example. To write a plug-in that replaces the background color,css('background')use the following code:
$.fn.background = function (BG) {return
this.css (' background ', BG);
|
Note that you can onlycss()return a value from, because the JQuery object has been returned. Therefore, method chaining is still working well.
I recommend that you use the JQuery plugin when you need to repeat your work. For example, if you need to useeach()a function to do the same thing over and over again, you can use a plug-in to do so.
Because the JQuery plugin is fairly easy to write, there are hundreds of options you can use. JQuery provides plug-ins for tabulation, fillet, slide shows, ToolTips, date selectors, and all the effects we can think of. For a complete list of plug-ins, see Resources .
The most complex, most widely used plug-in is the interface (Interface), an animated plug-in that handles sorting, drag-and-drop functionality, complex effects, and other interesting and complex user interfaces (users Interface,ui). The interface is as scriptaculous for JQuery as for Prototype.
Form Plug-ins are also popular and useful, and they allow you to easily submit forms in the background using Ajax. This plugin handles some of the most common situations: you need to intercept a form's commit event, find all the different input fields, and use these fields to construct an Ajax call.