jQuery Getting Started guide in Chinese (purely Reprinted)

Note: This article is purely reproduced, the original address: http://www.k99k.com/jQuery_getting_started.html

jQuery Getting Started guide in Chinese, translation plus examples, jQuery tutorials starting point

Chinese Translator: Keel

Article based on a step by step examples show jQuery works. Chinese translation is (add me add that) is as follows. For related comments or suggestions, please EMAIL this. Or in the BLOG in the message.

English original: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery <! - http://jquery.bassistance.de/jquery-getting-started.html -> , to thank the original author J ö rn Zaefferer This release has been sought original author agrees.

Description: In this tutorial, after release, have a few friends of the correction, made on the part of the amendment, but the updated version of the jQuery circumstances, tutorials, some of the content is out of date (especially version 1.3 or above), in loyal to the original basis, I will put this part of the supplement to be marked red, the hope that more front-end developers can view this article valuable, thank you! - 2009-3-10

Also I think that in the learning process, there are two API documents open at any time you want to see:

If you would like more information on jQuery and the plugin can visit the homepage .

The following part is the original translation:

jQuery Getting Started Tutorial

This guide is an explanation jQuery library, asking readers to know HTML (DOM) and some knowledge of CSS. It includes a simple Hello World example, selector and event based, AJAX, FX's usage, as well as how to make jQuery plug-ins. This guide includes a lot of code, you can copy them, and try to modify them to see the effect produced.


  1. Installation
  2. Hello jQuery
  3. Find me: Use selectors and events
  4. Rate me: Use AJAX
  5. Animate me (let me to life): Use the FX
  6. Sort me (my ordering): Use tablesorter plug (order form)
  7. Plug me: create your own plug-ins
  8. Next steps (Next)


First we need a jQuery library, the latest downloads can go here to find. This guide provides a basic package contains examples for download.

Download: jQuery Starterkit

(Translator Keel Note: Be sure to download this package, just look at the article does not practice, it is definitely impossible.)

After downloading unzip and then use your favorite text editor to open starterkit.html and custom.js these two files. (Translator Keel Note: These are the two examples of documents, all of the examples are made with these two examples, custom.js write jQuery code, starterkit.html observe the effect. Suggested editPlus open)

Now, we have made preparation for the conduct of the famous "Hello world" example.

Links in this chapter:

Hello jQuery

Before doing all the things we want to read and process the document jQuery DOM, must be included as soon as possible after the implementation of the DOM events, so we deal with a ready event as the beginning of the HTML document. Look at our open The custom.js this document, which has been prepared:

$(document).ready(function() {
        // do stuff when DOM is ready

Put a simple alert DOM event needs to finish loading, so we changed a little bit more complex task: the click on any link to display a alert.

$(document).ready(function() {
        $("a").click(function() {
                alert("Hello world!");

So that the page you click on a link will trigger the "Hello world" tips.

(Translator Keel Note: Please do the same code changes custom.js and save, then use your browser to open starterkit.html observed effect.)

Let us look at what is the meaning of these changes. $ ("A") is a jQuery selector (selector), where it selects all of a label (Translator Keel Note: that <a> </ a>), $ number is the jQuery "class" (jQuery " class ") of a nickname, so $ () constructs a new jQuery object (jQuery object). Function click () is a method of the jQuery object, which binds a click event to all the selected tab (here is all a label), and implemented in the event triggered the alert methods it provides.

There is a similar function to be line of code:

<a href="#">Link</a>

Difference between clear, do not need to use jQuery to write each a label onclick Event , so we have a neat structured document (HTML) and a Xingwei document (JS), to the behavior of structures with Fenkai the Mudi, As we seek to use the same CSS.

Here we will learn more about selectors and events.

Links in this chapter:

Find me: Use selectors and events

jQuery provides two ways to select html of the elements, the first is to use CSS and Xpath selectors together to form a string to send to the jQuery constructor (eg: $ ("div> ul a")); second jQuery object species is several methods (methods). Both methods can also be mixed together.

To test these selectors, we try to select and modify our starterkit.html the first ordered list.

First we need to select the list itself, the list has an ID called "orderedlist", written with the usual javascript document.getElementById ("orderedlist"). In jQuery, we do:

$(document).ready(function() {

Here's starterkit a CSS style on the red attached to the orderedlist (Translator Keel Note: Reference test package css directory core.css, which defines the red style). So, before you refresh the starterkit.html, you will see the first ordered list (ordered list) background becomes red discoloration, while the second ordered list has not changed.

Now, let us add some new styles to the list of child nodes.

$(document).ready(function() {
        $("#orderedlist > li").addClass("blue");

In this way, all orderedlist are attached in the li style "blue".

Now let us make a more complex, when the mouse li object style when the top and remove the switch, but only the last element in the list on the force.

$(document).ready(function() {
        $("#orderedlist li:last").hover(function() {
        }, function() {

There are a large number of similar CSS and XPath examples, more examples and a list can here be found. (Translator Keel Note: see text entry, practice in individual, to know more after the entry, so this would sooner or later a few links to a must-see! Will not have to translate it ...^_ ^!)

Each onXXX event are valid, such as onclick, onchange, onsubmit, etc., have equal representation jQuery (Translator Keel Note: jQuery does not like onXXX, so have changed to XXX, removed on). Other events , such as ready, and hover, also provides a corresponding method.

You can Visual jQuery to find all the events list, under the Events section.

With these selectors and events you can already do a lot of things, but here there is a more good stuff!

$(document).ready(function() {
        $("#orderedlist").find("li").each(function(i) {
                $(this).html( $(this).html() + " BAM! " + i );

find () so that you have selected element in the search for the conditions, so $ ("# orderedlist). find (" li ") as $ (" # orderedlist li ") the same. each () method to iterate all li, and on this basis can be more treatment. Most of the methods, such as addClass (), can use their own each (). In this example, html () is used to obtain the html for each li text, append some text, and the set li of html text. (Translator Keel Note: you can see from this example. html () method is to obtain the object of html code, and. html ('xxx') is set 'xxx' is the object of the html code)

Another frequently encountered task is not covered by jQuery DOM elements on the call of some method, imagine a way in your success with AJAX after the submission of the reset:

$(document).ready(function() {
        // use this to reset a single form
        $("#reset").click(function() {

(Translator Keel Note: This author has written a form of id form, the source file has <form>, this is a very bad wording, you can change this ID form1 or testForm, and then use $ ("# form1 ") or $ (" # testForm ") to represent it, and then test it.)

This code select all the ID for the "form" elements, and in its first call on a reset (). If you have more than one form, you can do:

$(document).ready(function() {
        // use this to reset several forms at once
        $("#reset").click(function() {
                $("form").each(function() {

(Translator Keel Note: Please note that the code must be written personally and in the starterkit.html custom.js test results can be appreciate! Necessary to observe starterkit.html the html code)

So you click the Reset link, select the document on all the form elements, and they have implemented a reset ().

You may have to face another problem is that certain elements do not want to be selected. jQuery provides a filter () and not () method to solve this problem. filter () to filter to reduce the expression of selected items do not meet, not () is used to remove all the filter expressions are choices. considered a disorder of the list, you want to select all child elements with no ul The li element.

$(document).ready(function() {
        $("li").not(":has(ul)").css("border", "1px solid black");// Originally  $("li").not("[ul]").css("border", "1px solid black");

This code select all li elements, then removes a ul li element child elements. Refresh your browser, all the li element has a border, only ul li element child elements of that exception.

(Translator Keel Note: Please note that experience is extremely convenient for the css () method, and be sure to remind observe actual test results, for example, from another CSS style it? Add a CSS style it? Like this: $ ("li" ). not ("[ul]"). css ("border", "1px solid black"). css ("color", "red");)

The above code in the [expression] syntax is XPath from, you can sub-elements and attributes (elements and attributes) used as filters, for example, you may want to select all links with the name attribute:

$(document).ready(function() {
        $("a[name]").css("background-color","#eee"); // Originally  "$("a[@name]").background("#eee");" In jQuery1.2 and above versions  ,@ The symbol should be removing, background method  css Replace method

The code name attribute to all links with adding a background color. (Translator Keel Note: This color is too obvious, and proposals in $ ("a [name]"). Css ("background-color", "# eee");) [Note: jQuery1.2 and above version, @ symbol should be removed, no explanation below]

More commonly, by name to select the link, you may need to select a feature links href attribute, which under different browsers href understanding may be inconsistent, so some of our matches ("*=") of way instead of exact match ("="):

$(document).ready(function() {
        $("a[href*=/content/gallery]").click(function() {
                // do something with all links that point somewhere to /content/gallery

Until now, the selector is used to select sub-elements or filter elements. Another case is the choice of one or the next element, such as a FAQ page, the answer will first hide, when the problem hits, the answer is displayed, jQuery code:

$(document).ready(function() {
        $('#faq').find('dd').hide().end().find('dt').click(function() {
         var answer = $(this).next();
         if (answer.is(':visible')) {
         } else {

Here we use the expressions of some chain to reduce the amount of code, it seems easier to understand and more intuitive. Like '# faq' selected only once, use end () method, the first find () method end (undone), so we can then later to find ('dt'), without the need to write $ (' # faq '). find (' dt ').

In the Click event, we use $ (this). Next () to find dt a dd element immediately following it so that we can quickly choose to click on the question below to be the answer.

(Translator Keel Note: This example is really cool, FAQ's answer could shrink! From the use of next () idea to have a lot to achieve these results we need to digest, pay attention to if (answer.is (': visible' )) usage, attention answer.slideUp (); do not know where I quickly check the most mentioned at the beginning of the two must-see API documentation)

In addition to selecting the elements with the level outside, you can choose the parent element. Maybe you want a certain article in the user mouse over a link, its parent element - that is, the article highlighted in this section, try this:

$(document).ready(function() {
        $("a").hover(function() {
        }, function() {

Test results can be seen that certain of the link moved to the article, spend it in a paragraph highlight all style, and later restored to their original removal.

(Translator Keel Note: highlight is core.css style defined, you can change it, pay attention here to have a second function () This is the hover method of characteristics, in the API documentation inspection hover, there are examples of the above )
Before we continue, let's take a look at this step: jQuery will make code much shorter and thus easier to understand and maintain, the following is the $ (document). Ready (callback) abbreviation method:

$(function() {
        // code to execute when the DOM is ready

Hello world apply to our case, it can be:

$(function() {
        $("a").click(function() {
                alert("Hello world!");

Now, we do have the basic knowledge, we can further explore the other side of things, starting from the AJAX!

Links in this chapter:

Rate me: Use AJAX

In this section we write a little AJAX application, it could rate things (translation Keel Note: that is to vote on certain things), as seen above, the same as in youtube.com.

First we need some server-side code, this example uses a PHP file, read the rating parameters and then return the total number and average rating. Look rate.php code.

While these examples may not use AJAX to achieve, but the show we will not do so, we generate a DIV container with jQuery, ID yes "rating".

$(document).ready(function() {
        // generate markup
        var 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) {
                // send requests
                $.post("rate.php", {rating: $(this).html()}, function(xml) {
                        // format result
                        var result = [
                                "Thanks for rating, current average: ",
                                $("average", xml).text(),
                                ", number of votes: ",
                                $("count", xml).text()
                        // output result
                } );

This code generates a 5 link, and they are appended to the id as "rating" container, when one of the links is clicked, the link marked with rating scores will be sent to parameter rate.php, then, the results XML format will transfer from the server back to the container, replace these links.

If you do not have one installed PHP in webserver, you can look at this online example.

The example does not use javascript to achieve access to softonic.de click "Kurz bewerten!"

More AJAX method can here be found, or to see API documentation the following AJAX filed under AJAX.

(Translator Keel Note: this online instance of access from home or slower, when clicked, will be a while to see results, you can modify it to consider, such as with loading, plus another vote after vote in the return links. In addition, this example there are still many areas for further digestion, the place can not read, please refer to API documentation.)

A load content using AJAX frequent question is: When loading an event handler to an HTML document, also need to load the contents of the application of these events, you have to load the completed application in the content sentence of these events handle, to prevent repeat the code, you may use as a function:

// lets use the shortcut
$(function() {
        var addClickHandlers = function() {
                $("a.clickMeToLoadContent").click(function() {
                        $("#target").load(this.href, addClickHandlers);

Now, addClickHandlers only after the completion of the implementation of the DOM loading time, which is every time a user clicks the link with clickMeToLoadContent the style and content loading is completed.

Please note that addClickHandlers function is defined as a local variable, instead of global variables (such as: function addClickHandlers () {...}), This is done to prevent another conflict with global variables or functions.

Another common problem is on the callback (callback) parameters. You can specify an extra parameter callback method, this simple approach is contained in a callback method in other function:

// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
var 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]); } );

Use a simple AJAX, we can think that has been very "web2.0", but until now, we still lack a number of cool effects. The next section will discuss these results.

Links in this chapter:

Animate me (let me to life): Use the FX

Some dynamic effects can be used to express show() and hide():

$(document).ready(function() {
        $("a").toggle(function() {
        }, function() {

You can animate() together to create some effects, such as starting to prove a sliding effect with:

$(document).ready(function() {
        $("a").toggle(function() {
                        height: 'hide',
                        opacity: 'hide'
                }, 'slow');
        }, function() {
                        height: 'show',
                        opacity: 'show'
                }, 'slow');

A lot of good results can be accessed Interface plugin Collection . This site provides a lot of demos and documentation

These effects plug-ins are located in front of jQuery plug-in list, of course, there are many other plug-ins, such as our order form referred to plug the next chapter.

Links in this chapter:

Sort me (my ordering): Use tablesorter plug (order form)

This form allows us to sort plug-ins on the client to sort by a column, the introduction of jQuery and this plugin js file, and then tell what plug-ins you want to have a sorting table.

To test this example, first starterkit.html add this line of code like the following:

<script src="lib/jquery.tablesorter.js" type="text/javascript"></script>

Then can be transferred do not need:

$(document).ready(function() {

Now click on the form the first line of head region, you can see the sort of results, click again wrestled over the order will be arranged.

This form can also add some highlights of the results, we can do such a interlaced background color (zebra) effects:

$(document).ready(function() {
                stripingRowClass: ['odd','even'],       // Class names for striping supplyed as a array.
                stripRowsOnStartUp: true                // Strip rows on tableSorter init.

More on this plug-in examples and documentation can be tablesorter home to find.

Almost all of the special pieces are so used: the first plug-js include file, and then some elements of the definition of the use of plug-ins, of course, there are some parameter options can be configured

Frequently updated list of available jQuery plug-official station on the jQuery site to find.

When you more often when using jQuery, you will find to your own code packaged into plug-in is useful, it can easily let your company or other person to reuse. The next chapter we will talk about how to build an own plug-ins.

Links in this chapter:

Plug me: make your own plug-ins

Write its own jQuery plugin is very easy, if you do follow the principle, can easily combined with others to use your plug-in.

  1. For your plug-in a name, which in this case we call it "foobar".
  2. Create a file like this: jquery. [Yourpluginname]. Js, for example we create a jquery.foobar.js
  3. Create one or more plug-in method, using the jQuery object inherits methods, such as:
    jQuery.fn.foobar = function() {
            // do something
  4. Optional: Create a function to help explain, such as:
    jQuery.fooBar = {
            height: 5,
            calculateBar = function() { ... },
            checkDependencies = function() { ... }

    You can now use your plug-in help functions of:

    jQuery.fn.foobar = function() {
            // do something
            // do something else
  5. The optional l: Create a default initial parameter configuration, these configurations can be set by the user, such as:
    jQuery.fn.foobar = function(options) {
            var settings = {
                    value: 5,
                    name: "pete",
                    bar: 655
            if(options) {
                    jQuery.extend(settings, options);

    Can now be configured without any use of plug-ins, and the default parameters in effect at this time:


    Or adding the definition of these parameters:

            value: 123,
            bar: 9

If you release your plugin, you should also provide some examples and documentation, most of the plug-in with these good reference document.

You should now have the basis to write a plug-in, so we try to use this knowledge to write its own plug-ins.

Many people try to control all of the radio or checkbox is selected, for example:

$("input[type='checkbox']").each(function() {
        this.checked = true;
        // or, to uncheck
        this.checked = false;
        // or, to toggle
        this.checked = !this.checked;

Note: jQuery1.2 and above, select the checkbox should be used for all input: checkbox, so the first line of code above can be written as:
$ ('Input: checkbox'). Each (function () (

Anyhow, when you arise each time the code, you should rewrite the above code to construct a plug-in, very directly:

$.fn.check = function() {
        return this.each(function() {
                this.checked = true;

This plug-in now can be used:


Note: jQuery1.2 and above, select the checkbox should be used for all input: checkbox Original: $ ("input [type = 'checkbox']"). check ();

Now you should also write uncheck () and toggleCheck () a. But first, a pause, let the plug-in to receive some of the parameters.

$.fn.check = function(mode) {
        var mode = mode || 'on'; // if mode is undefined, use 'on' as default
        return this.each(function() {
                switch(mode) {
                case 'on':
                        this.checked = true;
                case 'off':
                        this.checked = false;
                case 'toggle':
                        this.checked = !this.checked;

Here we set the default parameters, so the "on" parameter is omitted is also possible, of course, you can add "on", "off", or "toggle", such as:


If you have more than one parameter settings a little bit complicated, when in use If you want to set the second parameter, will have to write in the first parameter position null.

Plug-ins from the previous chapter's tablesorter use, we can see all the parameters can be omitted either to use or by a key / value pairs to re-set each parameter.

As a practice, you can try to rewrite the chapter features a plug-in. This plug-in skeleton should be like this:

$.fn.rateMe = function(options) {
        var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context

        var 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)

If you want a better javascript development, I suggest you use a name FireBug for firefox plug-in. It offers breakpoints (much stronger than the alert), observed changes in DOM functions, and many other beautiful

If you still have unresolved questions or new ideas and suggestions, you can use jQuery mailing list for jQuery mailing list .

Anything on this guide, you can write mail to the author or a comment in his log: blog .

Translation of this guide on any matter, you can write mail to me. or in the BLOG in the message.

What ...

Much to thank John Resig has created such a good library! Thank John jQuery community provides so much for the coffee and everything else!

© 2006, Jö rn Zaefferer - last Update: 2006-09-12

English translation: Keel Last updated :2006-12-13 - Last Updated: 2009-3-10 <! - 2006-12-13 -> to visit Home

<script type="text/javascript"> </ script> <script src="http://www.google-analytics.com/ga.js" type="text/javascript"> </ script> <script type = "text / javascript"> </ script>

分类:Web 时间:2010-03-23 人气:429
blog comments powered by Disqus


  • Ajax Application Development: A Practical Guide 2010-08-10

    The current focus on Web application development are essentially rich Internet applications ( Rich Internet Application , RIA) launched. Implementation of RIA technologies are many: Ajax , Flash , JavaFX and Sliverlight so. Ajax technology is that it

  • jQuery Getting Started guide in Chinese, translation plus examples, jQuery tutorials starting point 2010-06-19

    jQuery Getting Started Tutorial This guide is an explanation jQuery library, asking readers to know HTML (DOM) and some knowledge of CSS. It includes a simple Hello World example, selector and event based, AJAX, FX's usage, as well as how to make jQu

  • 1.14 's blog on Yii Framework Tutorial (translation) to establish and display the comment _ _ Section 28 2010-09-22

    4.2 The establishment Show Comments This section, to achieve Comments display and build. In order to improve interaction with the user, I would like the user immediately after the prompt completion of each input may encounter errors. This need to und

  • ubuntu 8.10 install a comprehensive guide to Oracle 10G Enterprise Edition 2011-01-03

    ubuntu 8.10 install a comprehensive guide to Oracle 10G Enterprise Edition First, the system update to the latest (there may need to manually install a package libaio1) 1. Increase the swap partition (as required to determine whether to add) Installa

  • Django Resource List 2010-12-13

    Recently, we often see Django in this forum related to the extended introduction, and its an extension to write a post, that did not quite need it. Django before finishing the list of resources, from my turn on the wiki. Django find resources, the of

  • [Change] Apache and Tomcat combination of clustering and load balancing to achieve 2010-04-28

    Combination of Apache and Tomcat clustering and load balancing to achieve this basic information from the easy Apache, Tomcat clustering and load balancing, records made by the practical operation experiences, met some access, and individual areas ba

  • Adobe AIR Developer Toolbox: Resources and Guide 2009-06-30

    AIR recent study found a good article, articles, translation of, and for all to share. Original Address: http://www.smashingmagazine.com/2009/04/07/adobe-air-developers-toolbox-resources-and-tutorials/ Is to generate an electronic version, download a

  • 128 ajax / javascript framework 2010-07-30

    128 ajax / javascript framework AJAX framework can help us to rapidly develop through JavaScript calling WebService (Server Page) pages, but not required to submit the entire page. Recent web applications use AJAX to improve the pages can be interact

  • 128 ajax / javascript frameworks 2010-07-30

    128 ajax / javascript framework AJAX framework can help us to rapidly develop through JavaScript calling WebService (Server Page) pages, but not required to submit the entire page. Recent web applications use AJAX to improve the pages can be interact

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.118 (s). 10 q(s)