jquery Chinese starter guide, translation plus example, jquery start Tutorial _ Basics

Source: Internet
Author: User
Tags documentation extend php code xpath xpath examples jquery library

jquery Chinese starter guide, translation plus examples, jquery's starting point tutorial

Translator of Chinese version: Keel

This article is a step-by-step illustration of how jquery works, based on an example. The Chinese translation (add my supplementary note) is as follows. If you have relevant comments or suggestions please write a reply to my BLOG or EMAIL to inform.

English Original: http://jquery.bassistance.de/jquery-getting-started.html, thank the original author Jörn zaefferer

The original author has been consulted on this issue.

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

  • http://jquery.com/api/
  • http://visualjquery.com/

The following sections are translated into the original text:

jquery Starter Guide Tutorial

This guide is a description of the jquery library that requires readers to understand some common sense of HTML (DOM) and CSS. It includes a simple Hello World example, selector and event basics, AJAX, FX usage, and how to make jquery plug-ins. This guide includes a lot of code, and you can copy them and try to modify them to see what happens.

Content Summary

  1. Installation
  2. Hello JQuery
  3. Find me: Using selectors and events
  4. Rate me: Using Ajax
  5. Animate me (Make me vivid): Using FX
  6. Sort me (order me): Using the Tablesorter plug-in (table sort)
  7. Plug me: Making your own plug-ins
  8. Next Steps (Next)

Installation

To begin with, we need a library of jquery, and the latest downloads can be found here. This guide provides a package for download that contains a basic instance.

Download: JQuery Starterkit

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

Unzip it after downloading, and then use your favorite text editor to open the two files starterkit.html and custom.js. (Translator Keel Note: These two are examples of files, all examples are made with these two examples, custom.js write jquery code, starterkit.html observation effect. Recommended to open with EditPlus)

Now we have done everything we can to make this famous "Hello World" example.

RELATED LINKS in this chapter:

  • Starterkit
  • JQuery Downloads

Hello JQuery

Before we do everything, we want jquery to read and process the DOM of the document, we have to start executing the event as soon as possible after the DOM is loaded, so we use a ready event as the beginning of the processing of the HTML document. Look at the file we opened custom.js. :

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

Put a simple alert event in the need to wait for the DOM to complete loading, so we make the task a little bit more complicated: Display an alert when clicking on any link.

$ (document). Ready (function () {
	$ ("a"). Click (function () {
		alert ("Hello world!");
	});

This will trigger this "Hello world" hint when you click on a link in the page.

(Translator Keel Note: Please follow this code to modify custom.js and save, and then use the browser to open starterkit.html observation effect. )

Let's take a look at what these changes mean. $ ("a") is a jquery selector (selector), where it selects all the A tags (translator keel note: <a></a>), and the $ number is a nickname for the jquery "class" (jquery "class"), So $ () constructs a new jquery object (jquery objects). The function click () is a method of this jquery object that binds a click event to all selected tags (here is all a tag) and executes the alert method it provides when the event is triggered.

Here's a code for similar functions:

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

The difference is obvious, with jquery, you don't need to write the OnClick event on each a tab, so we have a neat structure document (HTML) and a behavioral document (JS) that separates the structure from the behavior, just as we would use CSS to pursue.

Below we will learn more about selectors and events.

RELATED LINKS in this chapter:

    • JQuery Base
    • JQuery Expressions
    • JQuery Basic Events

Find me: Using selectors and events

jquery offers two ways to select the elements of HTML, the first of which is to combine CSS and XPath selectors to form a string to be routed to JQuery's constructor (such as: $ ("DIV > Ul a")) The second is a few methods (methods) with jquery objects. These two ways can also be combined to mix.

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

In the beginning, we need to select the list itself, which has an ID called "Orderedlist", and the usual JavaScript notation is document.getElementById ("Orderedlist"). In jquery, We do this:

$ (document). Ready (function () {
	$ ("#orderedlist"). AddClass ("Red");

This adds a CSS style red from the Starterkit to the Orderedlist (translator keel Note: The CORE.CSS in the CSS catalog in the reference test package, which defines the red style). So after you refresh the starterkit.html, you'll see that the first sequence table (ordered list) has a background color that turns red, and the second ordered list doesn't change.

Now let's add some new styles to the child nodes of the list.

$ (document). Ready (function () {
	$ ("#orderedlist > Li"). addclass ("Blue");

In this way, all Li in the orderedlist has the style "blue" attached.

Now let's make it a little more complicated by switching the style when the mouse is over the Li object and moving it away, but 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 plenty of similar CSS and XPath examples, and more examples and lists can be found here. (Translator Keel Note: Introduction to see this article, self-cultivation in the individual, to want to know more after the introduction, so this paragraph of a few links will be required to see sooner or later!) It's not going to translate again ... ^_^!)

Every onxxx event, such as Onclick,onchange,onsubmit, has a jquery equivalent representation (translator keel Note: jquery does not like onxxx, so it's all changed to XXX, minus on). Other events, such as ready and hover, also provide a corresponding approach.

You can find all the list of events in Visual jquery, in the events section.

With these selectors and events you've been able to do a lot of things, but here's a much stronger good stuff!

$ (document). Ready (function () {
	$ ("#orderedlist"). Find ("Li"). each (function (i) {
		$ (this). HTML ($ (this). html () + "bam!" + i);
	});

Find () lets you make a conditional lookup in the element you have chosen, so $ ("#orderedlist"). Finding ("Li") is like $ ("#orderedlist Li"). Each () iterates over all of the Li, and can be done more on this basis. Most of the methods, such as addclass (), can be used with each of their own (). In this example, HTML () is used to get the HTML text of each Li, append some text, and set it to Li's HTML text. (Translator Keel Note: You can see from this example. The HTML () method is to get the object's HTML code, while. html (' xxx ') is the HTML code that sets ' xxx ' as an object)

Another frequently encountered task is to call some methods on a DOM element that is not covered by jquery, imagining a reset after you successfully submitted it in AJAX mode:

$ (document). Ready (function () {
	//Use this to reset a single form
	$ ("#reset"). Click (function () {
		$ ("#form") [0].reset ();
	});
};

(Translator Keel Note: Here the author will form ID also written form, the source file has <form id= "form", this is very bad writing, you can change this ID to Form1 or testform, and then use $ ("#form1") or $ ( "#testForm") to represent it, and then to test it. )

This code selects all elements with the id "form" and a reset () is called on the first. 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 note that you must write the code in the Custom.js in person and test the results on starterkit.html to experience!) Observe the starterkit.html HTML code if necessary)

After you click on the Reset link, you select all the form elements in the document and perform a reset () on them.

Another problem you may have to face is that you don't want certain elements to be selected. JQuery provides the filter () and the Not () method to solve this problem. Filter () Filters the expression to reduce the selected items that are not compliant, and not () to cancel all selected items that conform to the filter expression. Consider a unordered list, and you want to select all the LI elements that have no UL child element.

$ (document). Ready (function () {
	$ ("Li"). Not ("[UL]"). CSS ("Border", "1px solid Black");

This code selects all of the LI elements and then goes beyond the LI element that has no UL child element. After refreshing the browser, all the LI elements have a border, only the UL element of the LI element exception.

(Translator Keel Note: Please note that the most convenient CSS () method, and again, please be sure to test the actual observation effect, for example, to change the CSS style? Add a CSS style? Like this: $ ("Li"). Not ("[UL]"). CSS ("Border", "1px solid Black"). CSS ("Color", "red")

The [expression] syntax in the above code is from XPath and can be used as a filter on child elements and attributes (elements and attributes), for example, you might 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: This color is too inconspicuous, it is suggested to write $ ("a[@name]"). Background ("red");

A more common scenario is to select a link with name, and you may need to select a link with the characteristic href attribute, which may be inconsistent with the understanding of href in different browsers, so our partial match ("*=") replaces the exact match ("="):

$ (document). Ready (function () {
	$ ("a[@href *=/content/gallery]"). Click (function () {
		//do something with all Links, point somewhere to/content/gallery
	});

So far, selectors have been used to select child elements or filter elements. Another situation is to select the previous or next element, such as a FAQ page, the answer is first hidden, when the problem 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 chain expressions to reduce the amount of code, and it looks more intuitive and easier to understand. Like ' #faq ' was chosen only once, using the end () method, the first find () method ends (undone), so we can then continue to get (' DT ') in the back, without having to write $ (' #faq '). Look (' dt ').

In the Click event, we use $ (this). Next () to find a DD element immediately below the DT, which allows us to quickly select the answer under the clicked question.

(Translator Keel Note: This example is really cool, the answer in the FAQ can shrink!) From the idea of using next () to achieve these effects there are a lot of places we need to digest, pay attention to if (answer.is (': Visible ')) usage, pay attention to Answer.slideup (); don't know where to look at the first two required API documents

In addition to selecting elements of the same level, you can also select the elements of the parent level. You might want to try this when the user mouse moves to a link in a paragraph of the article, and its parent element-that is, this section of the article-is highlighted:

$ (document). Ready (function () {
	$ ("a"). Hover (function () {
		$ (this). Parents ("P"). AddClass ("highlight");
	, function () {
		$ (this). Parents ("P"). Removeclass ("highlight");
	});

The test effect can see that when you move to a link in a section of the article, it is all in the highlight style, removed and then returned to its original form.

(Translator Keel Note: Highlight is the style defined in Core.css, you can also change it, note that there is a second function () this is the characteristics of the hover method, please refer to the hover in the API documentation, which also has an example to illustrate)

Let's take a look at this step before we go: jquery makes the code shorter and easier to understand and maintain, and here is $ (document). Abbreviation for Ready (callback):

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

Applied to our Hello World example, you can do this:

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

Now that we have these basics in hand, we can go further and explore other things, starting with Ajax!

RELATED LINKS in 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: Using Ajax

In this section we write a small AJAX application that can rate something (in keel note: voting for something), as seen on YouTube.com.

First we need some server-side code, this example uses a PHP file, reads the rating parameter and returns the rating total and average. Take a look at the rate.php code.

While these examples can be implemented without Ajax, we don't do that, we use jquery to generate a div container with the id "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 (")). Fin D ("a"). Click (function (e) {
		e.preventdefault ();
		Send requests
		$.post ("rate.php", {rating: $ (this). html ()}, function (XML) {
			//format result
			var result = [
				"for rating, current average:",
				$ ("average", XML). Text (),
				", Number of votes:",
				$ ("Count ", XML). Text ()
			];
			Output result
			$ ("#rating"). HTML (Result.join ('));
		});
	}
;

This code generates 5 links and appends them to the ID "rating" container, and when one of the links is clicked, The score indicated by the link is sent to the rate.php in the form of a rating parameter, and the results are then passed back from the server side in XML and added to the container to replace the links.

If you don't have a webserver that has been installed in PHP, you can look at this online example.

Examples that do not use JavaScript implementations can be accessed softonic.de click "Kurz bewerten!"

More Ajax methods can be found from here, or look at the Ajax filed under Ajax under the API documentation.

(Translator keel Note: This online example from the domestic visit is relatively slow, click to wait for a while to see the results, you can consider to modify it, such as add loading, after the vote plus the return of the vote back link.) In addition, there are many areas where further digestion is needed, please refer to the API documentation where you do not understand. )

One common problem that occurs when you load content with Ajax is: When you load an event handle into an HTML document, you also need to apply these events to the loading content, and you have to apply the event handlers after the content has been loaded, and to prevent the code from recurring, you might use one of the following function:

Lets use the shortcut
$ (function () {
	var addclickhandlers = function () {
		$ ("a.clickmetoloadcontent"). Click (function () {
			$ ("#target"). Load (this.href, addclickhandlers);
		});
	Addclickhandlers ();
});

Now, Addclickhandlers only executes once after the DOM load completes, which is when the user clicks the link with clickmetoloadcontent and the content is loaded.

Note that the Addclickhandlers function is defined as a local variable, not a global variable (such as a function addclickhandlers () {...}) to prevent conflicts with other global variables or functions.

Another common problem is the parameters for callbacks (callback). You can specify a callback method with an additional parameter, simply by including the callback method in one of the 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 are need the context of the original handler, use apply:
$ (' a '). Click (Function (event) {handler.apply (this, [fo Obar]); } );

With simple Ajax, we can think of it as "web2.0", but we still lack some cool results so far. These effects are discussed in the next section.

RELATED LINKS in 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 (Make me vivid): Using FX

Some dynamic effects can be used show() and hide() represented by:

$ (document). Ready (function () {
	$ ("a"). Toggle (function () {
		$ (". Stuff"). Hide (' slow ');
	}, function () {
		$ (". Stuff"). Show (' fast ');
	};
});

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

$ (document). Ready (function () {
	$ ("a"). Toggle (function () {
		$ (". Stuff"). Animate ({
			height: ' Hide ',
			opacity: ' Hide '
		}, ' slow ');
	}, Function () {
		$ ('. Stuff '). Animate ({
			height: ' show '),
			Opacity: ' Show '
		}, ' slow ');
	};

Many good effects can be accessed by interface plugin collection. This site provides a lot of demos and documentation

These effect plug-ins are in front of the jquery plugin list, and of course there are a number of other plug-ins, such as the table-sorting plug-in we talked about in the next chapter.

RELATED LINKS in this chapter:

  • JQuery FX Module
  • Interface Plugin

Sort me (order me): Using the Tablesorter plug-in (table sort)

This table sorting plugin lets us sort by a column on the client, introduces jquery and the JS file of the plugin, and then tells the plugin which table you want to have the sorting function.

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

<script src= "Lib/jquery.tablesorter.js" type= "Text/javascript" ></script>

Then you can do this without:

$ (document). Ready (function () {
	$ ("#large"). Tablesorter ();

Now click the first line of the table and you can see the effect of the sort, click again to arrange in the reverse order.

This table can also add some highlight effect, we can do such an interlaced background color (zebra) Effect:

$ (document). Ready (function () {
	$ ("#large"). Tablesorter ({
		stripingrowclass: [' odd ', ' even '],	//Class Names for striping supplyed as a array.
		Striprowsonstartup:true		//Strip rows on Tablesorter init.
	});

More examples and documentation of this plugin can be found on the Tablesorter home page.

Almost all of the features are used in this way: first include the plug-in JS file, and then some elements to use the plug-in definition method, of course, there are some parameter options can be configured

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

When you use jquery more often, you'll find it useful to pack your own code into plug-ins that can easily be reused by your company or someone else. In the next chapter we'll talk about building a plugin of our own.

RELATED LINKS in this chapter:

    • Plugins for JQuery
    • Tablesorter Plugin

Plug me: Making your own plug-ins

Writing your own jquery plugin is very easy, and if you follow these guidelines, you can make it easier for others to combine your plug-ins.

    1. Take a name for your plugin, and 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 methods that use the way that you inherit the jquery object, such as:
      JQuery.fn.foobar = function () {
      	//do something
      };
    4. Optional: Create a function for the help description, such as:
      Jquery.foobar = {
      	Height:5,
      	calculatebar = function () {...},
      	checkdependencies = function () {...}}
      ;

      You can now use these helper functions in your plugin:

      JQuery.fn.foobar = function () {
      	//do something
      	jQuery.foobar.checkDependencies (value);
      	Do something else
      };
    5. Optional L: Creates a default initial parameter configuration, which can also be set by the user, such as:
      JQuery.fn.foobar = function (options) {
      	var settings = {
      		Value:5,
      		name: "Pete",
      		bar:655
      	};< C16/>if (options) {
      		jquery.extend (settings, options);
      	}
      };

      You can now use Plug-ins without any configuration, and the default parameters take effect at this time:

      $ ("..."). Foobar ();

      Or add these parameter definitions:

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

If you release your plugin, you should also provide some examples and documentation, most of which have these good reference documentation.

Now that you have the basics of writing a plugin, let's try to use that knowledge to write a plugin of our own.

Many people try to control whether all 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;
});

Whenever your code appears with each, you should rewrite the code above to construct a plugin, very directly:

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

This plugin can now be used in this way:

$ ("input[@type = ' checkbox ']"). Check ();

Now you should also be able to write uncheck () and Togglecheck (). But stop and let our plugin receive some parameters.

$.fn.check = function (mode) {
	var mode = Mode | | ' On '; If mode is undefined, use ' in ' as Default return
	This.each (function () {
		switch (mode) {case
		' on ':
			t His.checked = true;
			break;
		Case ' off ':
			this.checked = false;
			break;
		Case ' Toggle ':
			this.checked =!this.checked;
			break;
		}
	});

Here we set the default parameters, so it is OK to omit the "on" argument, and of course 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 setting that is slightly more complex, write null at the first parameter position if you want to set only the second argument when you use it.

From the Tablesorter plug-in usage in the previous chapter, we can see that you can either omit all parameters to use or reset each parameter with a Key/value pair.

As an exercise, you can try to rewrite the fourth chapter function as a plugin. The skeleton of this plugin should be like this:

$.fn.rateme = function (options) {
	var container = this;//instead of selecting a static container with $ ("#rating"), We use the JQuery context
	
	var settings = {
		URL: ' rate.php '
		//Put more defaults here
		//Remember to PU T a comma (",") after each pair, but is not on 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 better JavaScript development, it is recommended that you use a Firefox plugin called Firebug. It provides breakpoint debugging (much better than alert), a lot of beautiful features such as DOM changes, and so on.

If you still have unresolved questions, or new ideas and suggestions, you can use jquery's mailing list of jquery mailing list.

For anything about this guide, you can write mail to the author or post comments in his journal: blog.

For any translation of this guide, you can write mail to me or post comments in my diary: blog.

What else...

Thank you so much, John Resig, for creating such a good library!. Thanks to jquery community for John's so much coffee and everything else!

©2006, Jörn zaefferer-last update:2006-09-12

Chinese translation: Keel-last update: 2006-12-13

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.