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.

Summary

  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)


Installation


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() {
        $("#orderedlist").addClass("red");
});

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() {
                $(this).addClass("green");
        }, function() {
                $(this).removeClass("green");
        });
});

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() {
                $("#form")[0].reset();
        });
});

(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() {
                        this.reset();
                });
        });
});

(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')) {
             answer.slideUp();
         } else {
             answer.slideDown();
         }
     });
});

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() {
                $(this).parents("p").addClass("highlight");
        }, function() {
                $(this).parents("p").removeClass("highlight");
        });
});

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) {
                e.preventDefault();
                // 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
                        $("#rating").html(result.join(''));
                } );
        });
});

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);
                });
        };
        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() {
                $(".stuff").hide('slow');
        }, function() {
                $(".stuff").show('fast');
        });
});

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

$(document).ready(function() {
        $("a").toggle(function() {
                $(".stuff").animate({
                        height: 'hide',
                        opacity: 'hide'
                }, 'slow');
        }, function() {
                $(".stuff").animate({
                        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() {
        $("#large").tableSorter();
});

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() {
        $("#large").tableSorter({
                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
            jQuery.foobar.checkDependencies(value);
            // 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:

    $("...").foobar();
    

    Or adding the definition of these parameters:

    $("...").foobar({
            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:

$('input:checkbox').check();

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;
                        break;
                case 'off':
                        this.checked = false;
                        break;
                case 'toggle':
                        this.checked = !this.checked;
                        break;
                }
        });
};

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:

$("input[type='checkbox']").check();
$("input[type='checkbox']").check('on');
$("input[type='checkbox']").check('off');
$("input[type='checkbox']").check('toggle');

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>
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of jQuery Getting Started guide in Chinese (purely Reprinted)

  • Hibernate primary key strategy-sequence

    Today, the use of hibernate in the company encountered a troublesome problem, the use of hibernate when the primary key generation strategy set sequence, but always reported in the implementation could not get next sequence value of the error, then o ...

  • hibernate call stored procedure

    hibernate call stored procedure

  • hibernate using c3p0 connection pooling

    Private http://www.lifevv.com/tenyo/doc/20070605102040991.html c3p0 for open source's JDBC connection pool, with the release hibernate. This article describes how to use the hibernate configuration in c3p0. c3p0 connection pool configuration is v ...

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • Build flex + spring + blazeds + hibernate application

    Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries