Jquery Getting Started Guide
This Guide describes the jquery library and requires readers to understand some common knowledge about HTML (DOM) and CSS. It includes a simple hello world example, selector and event basics, Ajax and FX usage, and how to create jquery plug-ins. This Guide contains a lot of code. You can copy them and try to modify them to see the results.
Contents
- Install
- Hello jquery
- Find me: Use selector and event
- Rate me: Ajax
- Animate Me (Let me be vivid): Use FX
- Sort me (order me): Use the tablesorter plug-in (Table sorting)
- Plug me: Make your own plug-ins
- Next steps (next step)
Install
At the beginning, we need a jquery library. The latest download can be found here. This Guide provides a package containing the instance for download.
Download: jquery starterkit
(Translator keel Note: You must download this package. It is definitely not feasible to read articles without practice .)
Download and decompress the files. Then, use your most recent editor to open starterkit.html and custom. js. (Translator keel Note: all examples are written using these two examples. m.js writes the jquerycode and starterkit.html observes the effect. editplus is recommended)
Now we have made all preparations for this famous "Hello World" example.
Links to this chapter:
- Starterkit
- Jquery downloads
Hello jquery
Before doing everything, we need jquery to read and process the document's Dom, and we must start to execute the event as soon as possible after Dom loading, we use a ready event as the start to process HTML documents. look at the M m we opened. JS file, which is ready:
$(document).ready(function() {// do stuff when DOM is ready});
Put a simple alert event and wait for the Dom to load it. So we make the task a little more complicated: an alert is displayed when you click any link.
$(document).ready(function() {$("a").click(function() {alert("Hello world!");});});
This will trigger the "Hello World" prompt when you click a link on the page.
(Translator keel Note: follow this code to modify custom.js and save it. Then, use a browser to open starterkit.html to observe the effect .)
Let's take a look at the meaning of these changes. $ ("A") is a jquery selector. Here, it selects all the tags (translator keel Note: <A> </a> ), $ is an alias for jquery "class". Therefore, $ () constructs a new jquery object ). The function click () is a method of this jquery object. It binds a click event to all selected tags (all a tags here ), the provided alert method is executed when the event is triggered.
Here is a code for similar functions:
<a href="#" onclick="alert('Hello world')">Link</a>
Obviously, jquery does not need to write onclick events on each a tag, so we have a neat structure document (HTML) and a behavior document (JS ), it achieves the goal of separating structure and behavior, just as we pursue with CSS.
Next we will learn more about selectors and events.
Links to this chapter:
- Jquery Core
- Jquery selectors
- Jquery events
Find me: Use selector and event
Jquery provides two methods to select HTML elements. The first method is to combine CSS with the XPath selector to form a string to be transmitted to the jquery Constructor (for example: $ ("div> ul a"); the second is to use several methods of the jquery object ). These two methods can also be combined for hybrid use.
To test the selection, we try to select and modify the first ordered list in starterkit.html.
In the beginning, we need to select the List itself. This list has an ID called "orderedlist", and the common JavaScript syntax is document. getelementbyid ("orderedlist "). in jquery, we do this:
$(document).ready(function() {$("#orderedlist").addClass("red");});
Append a CSS style red in starterkit to orderedlist (translator keel Note: Refer to core.css In the CSS directory of the test package, which defines the red style ). After you update starterkit.html, you will see that the background color of the first ordered list has changed to red, and the second ordered list has not changed.
Now, let's add some new styles to the list subnodes.
$(document).ready(function() {$("#orderedlist > li").addClass("blue");});
In this way, the style "blue" is appended to Li in all orderedlist ".
Now let's make it a little more complicated. When you move the mouse over the Li object and move it away, style switching will take effect only on the last element of the list.
$(document).ready(function() {$("#orderedlist li:last").hover(function() {$(this).addClass("green");}, function() {$(this).removeClass("green");});});
There are also a lot of examples similar to CSS and XPath, more examples and lists can be found here. (Translator keel Note: This article is for beginners. If you want to learn more after getting started, several links in this article will be required sooner or later! Will not translate again... ^_^ !)
Every onxxx event is valid, such as onclick, onchange, and onsubmit. There are jquery equivalent representation (translator keel Note: jquery does not like onxxx, so it is changed to XXX, remove on ). Other events, such as ready and hover, also provide corresponding methods.
You can find all the event lists in visual jquery, under the events column.
You can do a lot with these selectors and events, but here is a better thing!
$(document).ready(function() {$("#orderedlist").find("li").each(function(i) {$(this).html( $(this).html() + " BAM! " + i );});});
Find () allows you to search for conditions in the selected element, so $ ("# orderedlist). Find (" Li ") is like $ (" # orderedlist li. The each () method iterates all the Li resources and can perform more processing on this basis. Most methods, such as addclass (), can use their own each (). In this example, HTML () is used to obtain the HTML text of each Li, append some text, and set it to the HTML text of Li. (Translator keel Note: from this example, we can see that. html (character encoding is the HTML code of the object, and. html ('xxx') is the HTML code for setting 'xxx' as the object)
Another common task is to call some methods on the DOM element that is not covered by jquery. Imagine a reset after you successfully submit it using Ajax:
$(document).ready(function() {// use this to reset a single form$("#reset").click(function() {$("#form")[0].reset();});});
(Translator keel Note: here the author also writes the Form ID into form, and the source file has <Form ID = "form">, which is a very bad way to write, you can change this ID to form1 or testform, and then use $ ("# form1") or $ ("# testform") to represent it, And then perform a test .)
This code Selects all the elements with the ID "form" and calls a reset () on the first one (). If you have more than one form, you can do this:
$(document).ready(function() {// use this to reset several forms at once$("#reset").click(function() {$("form").each(function() {this.reset();});});});
(Translator keel Note: Please be sure to write the code in custom.js and test the effect on starterkit.html! Observe the HTML code of starterkit.html when necessary)
In this way, after you click the reset link, you select all form elements in the document and execute a reset () for them ().
Another problem you may want to face is that you do not want certain elements to be selected. Jquery provides the filter () and not () methods to solve this problem. Filter () uses a filter expression to reduce the selected items that do not match. Not () is used to cancel all selected items that match the filter expression. consider an unordered list. You want to select all Li elements without ul sub-elements.
$ (Document ). ready (function () {$ ("Li "). not (": Has (UL)" bar .css ("border", "1px solid black"); // The original version is $ ("Li "). not ("[ul]" bar .css ("border", "1px solid black ");});
This code Selects all the Li elements and removes the Li elements with UL sub-elements. After refreshing the browser, all the Li elements have a border, except the Li element of the UL sub-element.
(Translator keel Note: Pay attention to the very convenient CSS () method, and remind you again to test the observed effect, for example, change the CSS style? What about a CSS style? Like this: $ ("Li"). Not ("[ul]" ).css ("border", "1px solid black" ).css ("color", "Red ");)
In the above Code, the [expression] syntax comes from XPath and can be used as a filter on the child elements and attributes (elements and attributes). For example, you may want to select all links with the name attribute:
$ (Document ). ready (function () {$ ("A [name]" ground .css ("background-color", "# Eee "); // The original text is "$ (" A [@ name] "). background ("# Eee"); "in jquery1.2 and later versions, the @ symbol should be removed, and the background method should be replaced by the CSS method });
This Code adds a background color to all links with the name attribute. (Translator keel Note: The color is too insignificant. We recommend that you write $ ("A [name]" ).css ("background-color", "# Eee");) [Note: in jquery1.2 and later versions, the @ symbol should be removed, which is not described below]
A more common scenario is to select links by name. You may need to select a link with the href attribute, which may have different href understandings in different browsers, therefore, we partially match ("* =") to replace the full match ("= "):
$(document).ready(function() {$("a[href*=/content/gallery]").click(function() {// do something with all links that point somewhere to /content/gallery});});
Up to now, selectors are used to select child elements or filter elements. Another scenario is to select the previous or next element. For example, on a faq page, the answer is hidden first. When a question is clicked, the answer is displayed. The jquery code is as follows:
$(document).ready(function() {$('#faq').find('dd').hide().end().find('dt').click(function() {var answer = $(this).next();if (answer.is(':visible')) {answer.slideUp();} else {answer.slideDown();}});});
Here we use some chained expressions to reduce the amount of code, and it looks more intuitive and easier to understand. Like '# FAQ', it is selected only once. Using the end () method, the first find () method will end (undone ), therefore, we can continue to find ('dt') later without writing $ ('# FAQ '). find ('dt ').
In the click event, we use $ (this). Next () to locate the next dd element under DT, which allows us to quickly select the answer under the clicked question.
(Translator keel Note: This example is really cool. The answers in the FAQ can be reduced! There are many things that need to be digested from using next () to implementing these effects. Note that if (answer. is (': visible') usage, pay attention to answer. slideup (); if you don't understand it, check the two API documents that I mentioned at the beginning)
In addition to the element of the same level, you can also select the element of the parent level. When you move the user's mouse over a link in a certain segment of the article, its parent element is highlighted in this section of the article. Try this:
$(document).ready(function() {$("a").hover(function() {$(this).parents("p").addClass("highlight");}, function() {$(this).parents("p").removeClass("highlight");});});
The test results show that when you move the link to a certain section of the article, the section where it is located uses the highlight style. After the link is removed, it is restored to its original state.
(Translator keel Note: highlightis the style defined in core.css. You can also change it. Note that the second function () is a feature of the hover method. Please refer to hover in the API documentation, the example above is also described)
Before proceeding, let's take a look at this step: jquery will make the code shorter and easier to understand and maintain. below is the abbreviation of $ (document). Ready (callback:
$(function() {// code to execute when the DOM is ready});
In our Hello world example, we can:
$(function() {$("a").click(function() {alert("Hello world!");});});
Now that we have the basic knowledge, we can further explore other things, starting with Ajax!
Links to this chapter:
- Jquery API documentation
- Visual jquery-a categorized browsable API documentation
- Jquery expressions: CSS
- Jquery expressions: xpath
- Jquery expressions: custom
- Jquery Special Events
- Jquery Dom traversing
Rate me: Ajax
In this section, we have written a small Ajax application, which can rate something (translated as keel Note: voting for something), just as we saw on Youtube.com.
First, we need some server code. In this example, we use a PHP file to read the rating parameter and then return the total number and average number of rating. Let's take a look at the rate. PHP code.
Although these examples can be implemented without Ajax, We will not do that. We use jquery to generate a div container with the ID "rating ".
$(document).ready(function() {// generate markupvar ratingMarkup = ["Please rate: "];for(var i=1; i <= 5; i++) {ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";}// add markup to container and applier click handlers to anchors$("#rating").append( ratingMarkup.join('') ).find("a").click(function(e) {e.preventDefault();// send requests$.post("rate.php", {rating: $(this).html()}, function(xml) {// format resultvar result = ["Thanks for rating, current average: ",$("average", xml).text(),", number of votes: ",$("count", xml).text()];// output result$("#rating").html(result.join(''));} );});});
This code generates five links and appends them to the "rating" container. When one of the links is clicked, the score indicated by this link is sent to rate as the rating parameter. PHP. Then, the results will be passed back from the server in XML format and added to the container to replace these links.
If you do not have a webserver installed with PHP, you can look at this online example.
If you do not use JavaScript, you can access softonic.de and click "Kurz bewerten! "
For more Ajax methods, refer to the Ajax filed under Ajax in the API documentation.
(Translator keel Note: This online instance is still relatively slow to access from China. After you click it, it will take a while to see the result. You can consider modifying it, such as adding loading, after voting, add the return link for voting. In addition, there are still many areas to be further digested in this example. For more information, see the API documentation .)
An issue that often occurs when using Ajax to load content is: when loading an event handle to an HTML document, you also need to apply these events on the loaded content, you have to apply these event handles after the content is loaded. To prevent repeated code execution, you may use the following function:
// lets use the shortcut$(function() {var addClickHandlers = function() {$("a.clickMeToLoadContent").click(function() {$("#target").load(this.href, addClickHandlers);});};addClickHandlers();});
Now, addclickhandlers is executed only once after the Dom is loaded. This is after you click a link with the clickmetoloadcontent style and the content is loaded.
Note that the addclickhandlers function is defined as a local variable instead of a global variable (for example, function addclickhandlers (){...}), this is done to prevent conflicts with other global variables or functions.
Another common problem is the callback parameter. You can use an additional parameter to specify the callback method. The simple method is to include this callback method in another function:
// get some datavar foobar = ...;// specify handler, it needs data as a paramtervar handler = function(data) {...};// add click handler and pass foobar!$('a').click( function(event) { handler(foobar); } );// if you need the context of the original handler, use apply:$('a').click( function(event) { handler.apply(this, [foobar]); } );
After using simple Ajax, we can think that it is already very "Web2.0", but till now, we still have some cool effects. These results will be discussed in the next section.
Links to this chapter:
- Jquery Ajax Module
- Jquery API: Contains description and examples for append and all other jquery Methods
- Thickbox: A jquery plugin that uses jquery to enhance the famous lightbox
Animate Me (Let me be vivid): Use FX
Some dynamic effects can be usedshow()
Andhide()
To show:
$(document).ready(function() {$("a").toggle(function() {$(".stuff").hide('slow');}, function() {$(".stuff").show('fast');});});
You cananimate()
Combine to create some effects, such as a sliding effect with a gradual display:
$(document).ready(function() {$("a").toggle(function() {$(".stuff").animate({height: 'hide',opacity: 'hide'}, 'slow');}, function() {$(".stuff").animate({height: 'show',opacity: 'show'}, 'slow');});});
You can access the interface plugin collection for a lot of good results. This site provides a lot of demos and documentation
These effect plug-ins are located at the front of the jquery plug-in list. Of course, there are many other plug-ins, such as the table sorting plug-ins we will discuss in the next chapter.
Links to this chapter:
- Jquery FX Module
- Interface plugin
Sort me (order me): Use the tablesorter plug-in (Table sorting)
This table sorting plug-in allows us to sort by column on the client, introduce jquery and JS files of this plug-in, and then tell the plug-in which table you want to have the sorting function.
To test this example, first Add the following line of code in starterkit.html:
<script src="lib/jquery.tablesorter.js" type="text/javascript"></script>
Then you can call it like this:
$(document).ready(function() {$("#large").tableSorter();});
Now, click the head area of the first row of the table to see the sorting effect. Click it again to sort it in the descending order.
This table can also add some highlighted effects. We can do this as a background color (zebra line) effect:
$(document).ready(function() {$("#large").tableSorter({stripingRowClass: ['odd','even'], // Class names for striping supplyed as a array.stripRowsOnStartUp: true // Strip rows on tableSorter init.});});
For more examples and documents about this plug-in, you can find it on the tablesorter homepage.
Almost all features are used as follows: First include the JS file of the plug-in, and then use the plug-in-definition method on some elements. Of course, some Parameter options can be configured.
The list of frequently updated plug-ins can be found from jquery official site on the jquery site.
When you use jquery more often, you will find it useful to package your code into a plug-in, which can be easily reused by your company or others. in the next chapter, we will talk about how to build a plug-in.
Links to this chapter:
- Plugins for jquery
- Tablesorter plugin
Plug me: Make your own plug-ins
It is very easy to write your own jquery plug-in. If you follow the following principles, it will make it easy for others to use your plug-in.
- Name your plug-in. In this example, we call it "foobar ".
- Create a file like this: jquery. [yourpluginname]. js. For example, we create a jquery. foobar. js file.
- Create one or more plug-in methods that inherit jquery objects, such:
jQuery.fn.foobar = function() { // do something };
- Optional: Create a function for help instructions, for example:
jQuery.fooBar = { height: 5, calculateBar = function() { ... }, checkDependencies = function() { ... } };
You can now use these helper functions in your plug-in:
jQuery.fn.foobar = function() { // do something jQuery.foobar.checkDependencies(value); // do something else };
- Optional L: Create a default initial parameter configuration, which can be set by the user, for example:
jQuery.fn.foobar = function(options) { var settings = { value: 5, name: "pete", bar: 655 }; if(options) { jQuery.extend(settings, options); } };
Now you can use the plug-in without any configuration. The default parameters take effect at this time:
$("...").foobar();
Or add these parameter definitions:
$("...").foobar({ value: 123, bar: 9 });
If you release your plug-in, you should also provide some examples and documents, most of the plug-ins have these good reference documents.
Now you should have the foundation to write a plug-in. Let's try to write a plug-in with this knowledge.
Many people try to control whether all radio or checkbox is selected, for example:
$("input[type='checkbox']").each(function() {this.checked = true;// or, to uncheckthis.checked = false;// or, to togglethis.checked = !this.checked;});
Note: In jquery1.2 and later versions, input: checkbox should be used when selecting all checkpoints. Therefore, the first line of the above Code can be written as follows:
$ ('Input: checkbox'). Each (function (){
Whenever your code appears with each, you should rewrite the above Code to construct a plug-in, which is very grounded:
$.fn.check = function() {return this.each(function() {this.checked = true;});};
This plug-in can be used as follows:
$('input:checkbox').check();
Note: In jquery1.2 and later versions, all checkboxes should be selected using input: the original checkbox is: $ ("input [type = 'checkbox']"). Check ();
Now you should be able to write uncheck () and togglecheck (). But stop it and let our plug-in receive some parameters.
$.fn.check = function(mode) {var mode = mode || 'on'; // if mode is undefined, use 'on' as defaultreturn this.each(function() {switch(mode) {case 'on':this.checked = true;break;case 'off':this.checked = false;break;case 'toggle':this.checked = !this.checked;break;}});};
Here we set the default parameter, so it is also possible to omit the "on" parameter, of course, you can also add "on", "off", or "toggle", such:
$("input[type='checkbox']").check();$("input[type='checkbox']").check('on');$("input[type='checkbox']").check('off');$("input[type='checkbox']").check('toggle');
If more than one parameter is set, it will be a little complicated. If you only want to set the second parameter during use, write null at the first parameter location.
We can see from the usage of the tablesorter plug-in the previous chapter that you can omit all parameters or reset each parameter through a key/value pair.
As an exercise, you can try to rewrite the function in Chapter 4 into a plug-in. The skeleton of this plug-in should be like this:
$.fn.rateMe = function(options) {var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery contextvar settings = {url: "rate.php"// put more defaults here// remember to put a comma (",") after each pair, but not after the last one!};if(options) { // check if options are present before extending the settings$.extend(settings, options);}// ...// rest of the code// ...return this; // if possible, return "this" to not break the chain});