JQuery Chinese Getting Started Guide, translation plus example, jQuery's starting point tutorial

Source: Internet
Author: User
Document directory
  • What else...

English 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 contains a lot of code. You can copy them and try to modify them to see the results.

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. Here, it selects all the tags (translator Keel Note: <a> </a> ), $ is an alias for jQuery "class". Therefore, $ () constructs a new jQuery object ). The function click () is a method of this jQuery object. It binds a click event to all selected tags (all a tags here ), the provided alert method is executed when the event is triggered.

Here is a code for similar functions:

<a href="#" onclick="alert('Hello world')">Link</a>

Obviously, jQuery does not need to write onclick events on each a tag, so we have a neat structure document (HTML) and a behavior document (JS ), it achieves the goal of separating structure and behavior, just as we pursue with CSS.

Next we will learn more about selectors and events.

Links to this chapter:
  • JQuery 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");});

Append a CSS style red in starterkit to orderedlist (translator Keel Note: Refer to core.css In the CSS directory of the test package, which defines the red style ). After you update starterkit.html, you will see that the background color of the first ordered list has changed to red, and the second ordered list has not changed.

Now, let's add some new styles to the list subnodes.

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

In this way, the style "blue" is appended to li in all orderedlist ".

Now let's make it a little more complicated. When you move the mouse over the li object and move it away, style switching will take effect only on the last element of the list.

$(document).ready(function() {$("#orderedlist li:last").hover(function() {$(this).addClass("green");}, function() {$(this).removeClass("green");});});

There are also a lot of examples similar to CSS and XPath, more examples and lists can be found here. (Translator Keel Note: This article is for beginners. If you want to learn more after getting started, several links in this article will be required sooner or later! Will not translate again... ^_^ !)

Every onXXX event is valid, such as onclick, onchange, and onsubmit. There are jQuery equivalent representation (translator Keel Note: jQuery does not like onXXX, so it is changed to XXX, remove on ). Other events, such as ready and hover, also provide corresponding methods.

You can find all the event lists in Visual jQuery, under the Events column.

You can do a lot with these selectors and events, but here is a better thing!

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

Find () allows you to search for conditions in the selected element, so $ ("# orderedlist ). find ("li") is like $ ("# orderedlist li "). each () iterates all 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]").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() {$("a").hover(function() {$(this).parents("p").addClass("highlight");}, function() {$(this).parents("p").removeClass("highlight");});});

The test results show that when you move the link to a certain section of the article, the section where it is located uses the highlight style. After the link is removed, it is restored to its original state.

(Translator Keel Note: highlightis the style defined in core.css. You can also change it. Note that the second function () is a feature of the hover method. Please refer to hover in the API documentation, the example above is also described)

Before proceeding, let's take a look at this step: jQuery will make the code shorter and easier to understand and maintain. below is the abbreviation of $ (document). ready (callback:

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

In our Hello world example, we can:

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

Now that we have the basic knowledge, we can further explore other things, starting with AJAX!

Links to this chapter:
  • JQuery API documentation
  • Visual jQuery-A categorized browsable API documentation
  • JQuery Expressions: CSS
  • JQuery Expressions: XPath
  • JQuery Expressions: Custom
  • JQuery Special Events
  • JQuery DOM Traversing
Rate me: AJAX

In this section, we have written a small AJAX application, which can rate something (translated as Keel Note: voting for something), just as we saw on youtube.com.

First, we need some server code. In this example, we use a PHP file to read the rating parameter and then return the total number and average number of rating. Let's take a look at the rate. php code.

Although these examples can be implemented without AJAX, We will not do that. We use jQuery to generate a DIV container with the ID "rating ".

$(document).ready(function() {// generate markupvar ratingMarkup = ["Please rate: "];for(var i=1; i <= 5; i++) {ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";}// add markup to container and applier click handlers to anchors$("#rating").append( ratingMarkup.join('') ).find("a").click(function(e) {e.preventDefault();// send requests$.post("rate.php", {rating: $(this).html()}, function(xml) {// format resultvar result = ["Thanks for rating, current average: ",$("average", xml).text(),", number of votes: ",$("count", xml).text()];// output result$("#rating").html(result.join(''));} );});});

This code generates five links and appends them to the "rating" container. When one of the links is clicked, the score indicated by this link is sent to rate as the rating parameter. php. Then, the results will be passed back from the server in XML format and added to the container to replace these links.

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

If you do not use javascript, you can access softonic.de and click "Kurz bewerten! "

For more AJAX methods, refer to the AJAX filed under AJAX in the API documentation.

(Translator Keel Note: This online instance is still relatively slow to access from China. After you click it, it will take a while to see the result. You can consider modifying it, such as adding loading, after voting, add the return link for voting. In addition, there are still many areas to be further digested in this example. For more information, see the API documentation .)

An issue that often occurs when using AJAX to load content is: when loading an event handle to an HTML document, you also need to apply these events on the loaded content, you have to apply these event handles after the content is loaded. To prevent repeated code execution, you may use the following function:

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

Now, addClickHandlers is executed only once after the DOM is loaded. This is after you click a link with the clickMeToLoadContent style and the content is loaded.

Note that the addClickHandlers function is defined as a local variable instead of a global variable (for example, function addClickHandlers (){...}), this is done to prevent conflicts with other global variables or functions.

Another common problem is the callback parameter. You can use an additional parameter to specify the callback method. The simple method is to include this callback method in another function:

// get some datavar foobar = ...;// specify handler, it needs data as a paramtervar handler = function(data) { ...};// add click handler and pass foobar!$('a').click( function(event) { handler(foobar); } );// if you need the context of the original handler, use apply:$('a').click( function(event) { handler.apply(this, [foobar]); } );

After using simple AJAX, we can think that it is already very "web2.0", but till now, we still have some cool effects. These results will be discussed in the next section.

Links to this chapter:
  • JQuery AJAX Module
  • JQuery API: Contains description and examples for append and all other jQuery methods
  • ThickBox: A jQuery plugin that uses jQuery to enhance the famous lightbox
Animate me (Let me be vivid): Use FX

Some dynamic effects can be usedshow()Andhide()To show:

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

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

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

You can access the interface plugin collection for a lot of good results. This site provides a lot of demos and documentation

These effect plug-ins are located at the front of the jQuery plug-in list. Of course, there are many other plug-ins, such as the table sorting plug-ins we will discuss in the next chapter.

Links to this chapter:
  • JQuery FX Module
  • Interface plugin
Sort me (order me): Use the tablesorter plug-in (Table sorting)

This table sorting plug-in allows us to sort by column on the client, introduce jQuery and js files of this plug-in, and then tell the plug-in which table you want to have the sorting function.

To test this example, first Add the following line of code in starterkit.html:

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

Then you can call it like this:

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

Now, click the head area of the first row of the table to see the sorting effect. Click it again to sort it in the descending order.

This table can also add some highlighted effects. We can do this as a background color (zebra line) effect:

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

For more examples and documents about this plug-in, you can find it on the tablesorter homepage.

Almost all features are used as follows: First include the js file of the plug-in, and then use the plug-in-definition method on some elements. Of course, some Parameter options can be configured.

The list of frequently updated plug-ins can be found from jQuery official site on the jQuery site.

When you use jQuery more often, you will find it useful to package your code into a plug-in, which can be easily reused by your company or others. in the next chapter, we will talk about how to build a plug-in.

Links to this chapter:
  • Plugins for jQuery
  • Tablesorter Plugin
Plug me: Make your own Plug-ins

It is very easy to write your own jQuery plug-in. If you follow the following principles, it will make it easy for others to use your plug-in.

  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:

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.