jquery Getting Started

sponsored links

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


Chinese version of the translator: Keel


This article with examples based on a step by step description of the jQuery works. Present to the Chinese translation (add to my supplementary statement) is as follows. If the relevant comments or suggestions please EMAIL tell. Or in the BLOG in the comments.

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 publication of this article has been sought agreed to the original author.

Description: In this tutorial after the release, some netizens have been corrected, amended some of its content, but in jQuery updated version of the case, some elements of the tutorial is outdated (especially version 1.3 or above), in loyal to the original basis, I will put this part of the contents to be marked red, adding that the hope that more front-end developers can this article valuable advice, thank you! - 2009-3-10

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

If you want to learn more jQuery and plug-in information, visit the site home page.

The following sections of the original translation:



jQuery Getting Started Tutorial


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

Summary

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


Installation


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

Download: jQuery StarterKit

(Translator Keel Note: Be sure to download this package, looking at the article did not practice certainly will not do.)

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 two examples of documents, all of the examples make use of these two examples, custom.js to write jQuery code, starterkit.html observe the effect. EditPlus is recommended to open)

Now, we've done all preparations to carry out the famous "Hello world" example.

Of this chapter Related links:



Hello jQuery


Do all things, we want jQuery to read and process the document DOM, the DOM to be loaded as soon as possible after the implementation of the event, so we use a ready event as the beginning of dealing with HTML documents. A look at our open The custom.js this document, which is ready:

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

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

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

So that the page you click on a link will be triggered when the "Hello world" advice.

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

Let us look at what is the meaning of these changes. $ ( "a") is a jQuery selector (selector), where it chooses all of a label (the translator Keel Note: the <a> </ a>), $ number is the jQuery "class" (jQuery " class ") of a another name, so $ () constructs a new jQuery object (jQuery object). Function click () is the jQuery object a method, which binds a click event to all selected labels (in this case all of a label), and implemented in the event triggered the alert means it provides.

There is a similar function of the proposed line of code:

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

The difference is obvious, no need to use jQuery to write on each a label on the onclick event, so we have a neat structure of the document (HTML), and an action document (JS), to the structure and behavior that will separate the purpose of Just as we seek to use the same CSS.

Here we will learn more about selectors and events.

Of this chapter Related links:



Find me: the use of selectors and events


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

In order to test how these selectors, we have to try in our starterkit.html select and modify the first one ordered list.

A start, we need to select the list itself, this list has an ID called "orderedlist", usually written in javascript is document.getElementById ( "orderedlist"). In jQuery, we do this:

$(document).ready(function() {
        $("#orderedlist

").addClass("red");

});

Here starterkit in a CSS style on the red attached to the orderedlist (Translator Keel Note: The reference test suite in the css directory core.css, which defines the red style). So, before you set a starterkit.html, you will see the first ordered list (ordered list) background becomes pale red, while the second ordered list has not changed.

Now, let's 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's be a bit more complex, and when put the mouse on the top and remove the object li style when switching, but only the last element in the list take effect.

$(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 be here to be found. (Translator Keel Note: The entry-read this article, self-cultivation at the individual, in order to understand more, after the entry, so a few links, then sooner or later this should be a must-see! Will not be yet another bar ...^_ ^!)

Each one onXXX events are effective, such as onclick, onchange, onsubmit, which have jQuery equivalent representation (Translator Keel Note: jQuery does not like onXXX, so have turned into a 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 heading Events.

Use these selectors and events that you can already do a lot of things, but there is a greater good Dongdong!

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

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

Another frequently encountered task is not jQuery covered call some methods on DOM elements, 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 also written in the form of the id of the form, the source file has <form>, this is a very bad writing, you can use this ID into 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 one on the call of 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 these codes must be personally written in custom.js and in the starterkit.html test results in order to have experience! Starterkit.html when necessary, to observe the html code)

So you click the Reset link, select the document on all the form elements, and they all 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 the selected items do not meet, not () is used to cancel all line items are selected filter expressions. 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 go in addition to the li element child elements ul. Refresh your browser, all of the li element has a border, only the ul element that the child li elements of the exception.

(Translator Keel Note: Please note that to facilitate understanding of the polar css () method, and once again remind sure to observe the actual test results, for example, a change in CSS styles do? 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 might want to select all of the link 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 stripped  ,background The methods are css approach instead of the  
});

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

More common situation is to select the name link, you may need to select a feature of the link href attribute, which is under a different browser href understanding may be inconsistent, so some of our matches ("*=") of the way to replace the exact match ("="):

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

Until now, selectors are used to select sub-elements or filter elements. Another situation is the choice of one or the next one element, such as a FAQ page, the answer is first of all will be hidden, when the problem hits, the answer is displayed, 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 used some expressions chain to reduce the amount of code, it seems more intuitive easier to understand. Like '# faq' select only once, the use of end () method, the first find () method will end (undone), so we can then later to continue to find ( 'dt'), without the need to write $ ( ' # faq '). find (' dt ').

In the Click event, and we use $ (this). Next () to find the dt a dd element immediately following it so that we can quickly choose the following answers to the question is clicked.

(Translator Keel Note: This example is really too cool, FAQ's answer can be shrink! From the use of next () idea to the realization of these effects have a lot of places we need to digest, pay attention to if (answer.is ( ': visible' )) usage, note that 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 element with the class outside, you can choose the parent element. You may want certain users to mouse over a link to the article, its parent-level 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 to move certain articles of the link, it has to spend the whole segment in the highlight style, and later restored to their original removal.

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

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

Hello world apply to our example, it can be:

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

Now, we do have such a foundation of knowledge, we can further explore other aspects of things, starting from the AJAX!

Of this chapter Related links:



Rate me: the use of AJAX


In this section we write a small AJAX application, it can rate something (translated Keel Note: that is to vote for 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. Take a look at rate.php code.

Although these examples can also be achieved without using AJAX, but show that we do not do it, we use jQuery to generate a DIV container, ID is a "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 five links, and they are appended to the id as a "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 pass back from the server side, added to the container, replace these links.

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

Examples of non-use javascript to achieve access to softonic.de click "Kurz bewerten!"

More AJAX method can here be found, or take a look at API documentation the following AJAX filed under AJAX.

(Translator Keel Note: this online example from a domestic visit is still relatively slow, when clicked, we have to wait a while to see results, you can modify it to consider, such as combined loading, re-vote after the vote together with the return links. In addition, this example there are still many places where the need for further digestion, can not read the local please refer to API documentation.)

A load content using AJAX recurring 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 content after application of these events Sentence handle, in order to prevent duplication of the implementation of 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 implemented after the completion of the DOM loading time, which is every time a user clicks the link with the clickMeToLoadContent this style, and content loading is complete.

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

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

// 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 be considered to have very "web2.0", but until now, we are also missing some cool effects. The next section will discuss these effects.

Of this chapter Related links:



Animate me (allow me to life): the use of FX


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

$(document).ready(function() {
        $("a").toggle(function() {
                $(".stuff").hide('slow');
        }, function() {
                $(".stuff").show('fast');
        });
});

You can animate() together to create a number of effects, such as a slide with a Jianxian effect:

$(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-ins list, of course, there are many other plug-ins, such as our order form on the next chapter talked about plug-ins.

Of this chapter Related links:



Sort me (my ordering): Use tablesorter plug-in (table order)


This form allows us to sort plug-ins on the client side of a column to sort by 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 in 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 to:

$(document).ready(function() {
        $("#large").tableSorter();
});

Now click the first row of the table head area, you can see the effect of sorting, click again to lie down over the order will be arranged.

The table can also add some highlights of the results, we can make such an 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 about this plug-in examples and documentation can be tablesorter page to find.

Almost all of the special pieces are like this with this: first, include plug-in js file, and then some elements of the definition of the use of plug-in method, of course, there are some parameters of options can be configured

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

When you are more frequent use of jQuery, you will find your own code packaged into plug-in is very useful, it can easily make your company or other person to be reused. The next chapter we will talk about how to build one themselves plug-ins.

Of this chapter Related links:



Plug me: Create your own plug-ins


JQuery to write one's own plug-in is very easy, if you follow the principle of doing it, we can let other people easily integrated to use your plug-ins.

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

    You can now plug in your use of these helper function: the

    jQuery.fn.foobar = function() {
            // do something
            jQuery.foobar.checkDependencies(value);
            // do something else
    };
    
  5. The optional l: to create a default initial parameter configurations can also be set by the user on their own, 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 the need to make any use of plug-ins, and the default parameters of the entry into force at this time:

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

    Or the inclusion of these parameters are defined:

    $("...").foobar({
            value: 123,
            bar: 9
    });
    

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

Now you should have to write a plug-in basis, so we try to use this knowledge to write an own plug-ins.

Many people try to control all of the radio or a checkbox is selected, such as:

$("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 follows:
$ ( 'input: checkbox'). each (function () (

No matter what, when your code appears each time, 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 reads: $ ( "input [type = 'checkbox']"). check ();

Now you should be able to write uncheck () and toggleCheck () has. But the first stop and let some of the parameters of our plug-in to receive.

$.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, it will be "on" parameter is omitted is also possible, of course, can also be added "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 there is more than one parameter settings will be a little bit complicated, when in use If you want to set the second argument, they should write in the first argument position of null.

The tablesorter plug-in usage from the previous chapter, we can see that all the parameters can be omitted either to use or through a key / value pairs to re-set each parameter.

As an exercise, you can try to Chapter IV of the function of rewriting as 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 to do a better javascript development, it is recommended you use one called FireBug for firefox plug-in. It offers breakpoints debugging (much stronger than the alert), observed changes in DOM, and many other nice features

If you have unresolved problems, or new ideas and suggestions, you can use jQuery mailing list jQuery mailing List.

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

The translation of this guide on any matter, you can write mail to me. Or in the BLOG in the comments.

What ...


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

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

English translation: Keel was last updated :2006-12-13 - Last Updated: 2009-3-10 "! - 2006-12-13 -" Access Home


<script type="text/javascript"> var gaJsHost = (( "https:" == document.location.protocol)? "https: / / ssl.": "http://www." ;); document.write (unescape ( "% 3Cscript src = '" + gaJsHost + "google-analytics.com/ga.js' type = 'text / javascript'% 3E% 3C/script% 3E") ); </ script> <script src="http://www.google-analytics.com/ga.js" type="text/javascript"> </ script> <script type="text/javascript"> try (var pageTracker = _gat._getTracker ( "UA-333331-1"); pageTracker._trackPageview ();) catch (err) () </ script>
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of jquery Getting Started

  • jBPM Development Getting Started Guide

    Although the workflow is still immature stage of development, not even a recognized standard. But its application has already been launched in the Express, indicating the market's demand for job-flow framework are urgent and enormous. Backgrounds of o

  • Openfire Plugin Developer's Guide

    Introduction Openfire features plug-ins are enhanced. This document is a guide to developers to create plug-ins. The structure of a plug-in Plug-ins Plug-ins openfireHome stored in the directory. When deploying a plug-in jar or war file, it will automatic

  • JS charts extjs implementation tools can be combined

    OpenFlashChart brief introduction by valensoft 2009-1-10 8:29:00 OpenFlashChart is an open source Flash and Javascript to the technical foundation for the free chart, using it to create some very useful analysis of the effect of the statements of the char

  • Hibernate Inteceptor

    The end of the project stage, the client suddenly put forward a very troublesome but normal demand, the system records all changes must be carried out. Formats such as: 2004.1.1 12:30 Ikuya wind orders Sales Order Date 2004.1.2-> 2004.1.3 The firs ...

  • 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 ...

  • [Reprint] Java professionals required books and list of sites

    Concurrent Programming in Java: Design Principles and Patterns (Doug Lea) Concurrent Programming in Java: Design Principles and Patterns, 2nd edition (Doug Lea; Addison-Wesley, 1999 years) Java Concurrent Programming - Design principles and patterns (seco

  • In the servlet use Bean

    According to Sun's definition, JavaBean is a reusable software components. In fact JavaBean is a Java class, through the package into a property and methods of treatment of a function or a business object, referred to as bean. Because JavaBean is ...

  • 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 ...

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