[Reprinted] jquery Chinese Getting Started Guide, translation plus example, jquery's starting point tutorial

Source: Internet
Author: User
ArticleDirectory
    • What else...
Jquery Chinese Getting Started Guide, translation plus example, jquery start tutorial Chinese Version Translator: keel

This article describes how jquery works step by step based on examples. The following is a Chinese translation (add my additional instructions. If you have any comments or suggestions, please send a reply or email to your blog.

Http://jquery.bassistance.de/jquery-getting-started.html, author J örn zaefferer

This article has been published with the consent of the original author.

In addition, I think there are two API documents you can view at any time during the learning process:

    • Http://jquery.com/api/
    • Http://visualjquery.com/
The following is the original translation: 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 includes manyCodeYou can copy them and try to modify them to see the effect.

Contents
    1. Install
    2. Hello jquery
    3. Find me: Use selector and event
    4. Rate me: Ajax
    5. Animate Me (Let me be vivid): Use FX
    6. Sort me (order me): Use the tablesorter plug-in (Table sorting)
    7. Plug me: Make your own plug-ins
    8. 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, where it selects all a labels(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 Base
    • Jquery expressions
    • Jquery basic 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 ");});

Add 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... ^_^ !)

Each onxxx event is valid, such as onclick, onchange, and onsubmit, and has the jquery equivalent representation.(Translator keel Note: jquery does not like onxxx, so it is changed to XXX and on is removed). 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) has been (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 ("[ul]" bar .css ("border", "1px solid black ");});

This code Selects all the Li elements and removes the Li elements without 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]"). Background ("# Eee ");});

This Code adds a background color to all links with the name attribute.(Translator keel Note: The color is too obscure. We recommend that you write $ ("A [@ name]"). Background ("red ");)

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 () {$ (""). 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 part, we have written a small Ajax application, which can rate something.(Translated by keel Note: voting for something), As you can see 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 (""). click (function (e) {e. preventdefault (); // send requests $. post ("rate. PHP ", {rating: callback (this).html ()}, function (XML) {// format resultvar result = [" Thanks for rating, current average: ", $ (" average ", XML ). text (), ", number of votes:", $ ("count", XML ). text ()]; // output result $ ("# rating" example .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 () {$ (". 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 () {$ (""). toggle (function () {$ (". stuff "). hide ('low');}, function () {$ (". stuff "). show ('fast ');});});

You canAnimate ()Combine to create some effects, such as a sliding effect with a gradual display:

 
$ (Document ). ready (function () {$ (""). toggle (function () {$ (". stuff "). animate ({Height: 'hide ', opacity: 'hide'}, 'slow') ;}, function () {$ (". stuff "). animate ({Height: 'Show ', opacity: 'show'}, 'low ');});});

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.

    1. Name your plug-in. In this example, we call it "foobar ".
    2. Create a file like this: jquery. [yourpluginname]. js. For example, we create a jquery. foobar. js file.
    3. Create one or more plug-in methods that inherit jquery objects, such:
      Jquery. FN. foobar = function () {// do something };
    4. 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 somethingjquery. foobar. checkdependencies (value); // do something else };
    5. 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 ;});

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 [@ 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 });
Next steps (next step)

If you want to develop JavaScript better, we recommend that you use a Firefox plug-in named firebug. It provides many nice functions such as breakpoint debugging (much better than alert) and Dom observation.

If you still have unsolved problems or new ideas and suggestions, you can use jquery's email list jquery mailing list.

For anything about this guide, you can write a mail to the author or post a comment on his log: blog.

For translation of this Guide, you can write a mail to me or post a comment on my log: blog.

What else...

Thanks to John resig for creating such a good library! Thanks to jquery community for providing John with so much coffee and everything else!

2006, Jörn zaefferer-last update:

Article Source: http://www.k99k.com/jQuery_getting_started.html

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.