JQuery Experiment Tutorial

Source: Internet
Author: User
Tags event listener tag name chrome developer chrome developer tools ibm developerworks

JQuery Experiment Tutorial

Introduction to JQuery, syntax and event handling

JQuery has dramatically changed the way JavaScript code is written, with its unique, concise code style. This tutorial is based on instance code, explains how jquery is used, and appropriately analyzes the implementation of jquery. Also, this tutorial provides an online code editor that allows you to practice the writing of JQuery code online.

About jquery: Why use jquery

JQuery is a free, open source JavaScript library across browsers. Its core design idea is to "write less code and do more Things" (write lower do). JQuery provides a set of easy-to-use APIs. These APIs greatly simplify many aspects of the client (browser) programming process, including:

    • The traversal and manipulation of HTML DOM
    • Browser event Handling
    • AJAX (asynchronous JavaScript and XML) programming
    • Effects (such as animated effects)

In traditional client-side programming that uses javascropt+dhtml directly, developers have to write lengthy code. And, to make the code compatible with different browsers, we have to write extra code to handle these cross-browser issues. JQuery's design goal is to simplify client-side programming. It allows us to write concise code that saves on development time, which can be as powerful as it is compatible with multiple browsers.

Back to top of page

Get jquery: Get started with jquery

The JQuery Web site provides two ways to publish files. One is the compressed content of the file, and the other is the original file. The former file does not contain code comments and whitespace characters that are not needed during code execution, and is suitable for use in a production environment (formally used environment), which reduces the time required for file loading. The latter file contains detailed code comments that are suitable for use in development and test environments.

JQuery's: http://jquery.com/download/

After you download jquery, you can use it by referencing the jquery code with the script element in the appropriate Web page. As shown in Listing 1:

Listing 1. Referencing JQuery from a local site
<script src= ". /js/lib/jquery/1.9.1/jquery.js "></script>

We can also get jQuery directly from CDN services offered by companies such as Google and Microsoft. It does this by referencing the URL of the CDN service directly in a webpage that needs to use JQuery. For example, one of the pages that uses Google's CDN is shown in Listing 2:

Listing 2. Referencing JQuery from a CDN

The URL for a CDN provided by Microsoft is: http://ajax.aspnetcdn.com/ajax/jQuery/jQuery-1.9.1.js

Back to top of page

The first instance of Hello World:jquery

In the following example, we use jQuery to implement the ability to display the current time on a page.

Listing 3. Hello World
Initpage onload= "Initpage ()"><span id= "message" ></span></body>

From the above example (online example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=HelloWorld.htm)

In the code, we can see that the Initpage function is called after the page has finished loading. The function, when executed, adds a string representing the current time of the client within the HTML node with the ID message. You don't have to be anxious to understand the exact meaning of the above code. The following section describes the syntax of JQuery. Also, in this example we use the OnLoad property of the BODY element to bind the event handler (Initpage) just to facilitate discussion. A handy API for handling page load event bindings in JQuery is described later in this chapter.

Back to top of page

JQuery syntax: A new knowledge of temperature

Although JQuery is not a new language in itself. However, learning its grammar can help us to use it skillfully and flexibly. Looking back at our familiar CSS syntax, it's not hard to see how JQuery's syntax is similar to CSS.

The design idea of jQuery syntax is to "select elements and manipulate them". This is very similar to the syntax of a CSS rule. For example, to set the font color for an element with ID message in the page to blue and the font size to 17px, you can define the CSS rule as shown in Listing 4:

Listing 4. CSS Rule Examples
#message {color:blue;font-size:17px;}

Visible from the CSS rules above, we expect an action on the appearance of the element (the font color is set to blue, the font size is set to 17PX) is specified by the 2 attribute declarations "Color:blue" and "font-size:17px". The elements that are used for these operations are specified by the CSS selector "#message" as an element with an ID equal to "message".

In summary, a property declaration in a CSS rule describes the Appearance property action, and the selector specifies which elements to apply the corresponding property action to. 1 is shown below:

Figure 1. CSS rules

The syntax of jQuery is actually the syntax that mimics the CSS rules. Its syntax is as follows:

$ (selector). Action (Actionparameter);

This is a chain-style syntax. Therefore, the syntax above is equivalent to:

var objtargetelements;//the target element to which the action is to be objtargetelements=$ (selector);//Specify the target element//Call the relevant method of Objtargetelements, Operation of the target element objtargetelements.action (Actionparameter);

In the above syntax,

$: Dollar symbol is an alias for jquery core function jquery. Of course, "$" in JavaScript is a valid function name. The Selector parameter specifies a jQuery selector. The jquery selector is similar to the selector in CSS, which tells JQuery what elements we are ready to manipulate (action). Also, the various selectors in CSS have an equivalent selector in JQuery.

Action: This method specifies what to do with the element specified by selector. The Actionparameter parameter is an optional parameter and is determined by the method specified, and it changes depending on the method.

Therefore, the JQuery statement in Listing 3 corresponds to the following:

Listing 5.Query non-chained syntax examples
/*$ ("#message"). HTML ("Hello world, it's now:" +new Date (). toLocaleString ()); equivalent: */var objtargetelements;//the target element to which the action is to be applied Specifies that the target element is an element with an ID equal to message, uses the ID-based selector objtargetelements=$ ("#message"), or invokes the Objtargetelements HTML method to set the HTML content OB for the target element Jtargetelements.html ("Hello World, it's now:" +new Date (). toLocaleString ());

The return value of the $ function is a jQuery custom-like array of objects. The object's individual numeric subscripts represent the values that correspond to the individual elements that the selector matches.

For example, the $ function call in Listing 3, which specifies a selector expression based on the element ID for the $ function:

$ ("#message")

Its return value will satisfy the following conditional expression. Because the selector expression "#message" matches the only element with the ID of message:

document.getElementById ("message") ==$ ("#message") [0]

The object returned by the $ function also provides methods to manipulate the elements that the selector matches by invoking the related methods of the object. For example, in the code shown in Listing 3, we set the HTML content of the element matching the selector expression "#message" by calling the HTML method of the return object of the $ function.

To be more intuitive about the return value of the $ function, we recommend that you observe the return value of a specific $ function call through the expression Monitoring feature of the developer tool in Chrome (watch Expressions). 2 is shown below:

Figure 2.$ function return value

The syntax of jquery and the corresponding relationship 3 of the jquery statement in Listing 3 are as follows:

Figure 3. JQuery Syntax Examples

The object returned by the $ function provides a common method named each. Each method takes a parameter, which is a callback function. Each method calls the callback function one at a time for each element in the element that the selector expression matches, and passes the individual element and its corresponding index number as a parameter to the function. See below for an example.

Suppose you have multiple links in the page, and now you want to display the URLs of all the links in the page in the browser's console.

The page code looks like this:

Listing 6.$ function return value instance
<a href= "https://www.ibm.com/developerworks/cn/" target= "_blank" >IBM developerworks Chinese station </a><br/> <a href= "Https://www.ibm.com/developerworks" target= "_blank" >IBM developerworks</a><br/><a href= "/" target= "_blank" > Home </a><br/>

(online example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code= $FuncReturn. htm)

At this point, you can match multiple elements (all link elements in the page) with a selector based on the element name, and call the each method that returns the value of the $ function. Here, we define a callback function (which is usually an anonymous function, which facilitates code writing), as a parameter to each function. In this callback function, we print the URL of each link to the browser console, as shown in the listing 7 code:

Each method of listing 7.jQuery--an easy way to traverse a collection object
Use the element name-based selector to match all the link elements in the page $ ("a"). Each function (Index,ele) {///anonymous functions are used as parameters for each method to invoke Console.log ("link" +index+ ":" + ELE.HREF);//Go to the console to print the link URL});

Now, you might want to do an exercise to change the element with the ID tip so that it can be displayed in bold. We know that to make an element bold, just specify its CSS property font-weight as bold. In other words, to implement such a function, we need the selector is "#tip", the corresponding action is to modify the CSS properties. So the code for JQuery is:

$ ("#tip"). CSS ("Font-weight", "bold");

You can use the online Code Editor in this tutorial to write code directly to practice the code above:

Http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=HelloWorld.htm

The online code Editor effect looks like this:

Figure 4. Online Code Editor

Back to top of page

jquery selector: jquery tool

After understanding the syntax of jquery, we understand that selectors are a core concept in jquery. Here are a few common types of jQuery selectors. Most of these selectors we can find their shadow from CSS.

The developer tool expression monitoring feature in Chrome lets us visually see the various properties and methods of the return value of the function. Therefore, when we learn jQuery or even actually work, we can directly observe the elements of the specified selector expression through the Chrome browser's expression monitoring tool to determine in real time whether the selector expression you want to use is correct.

Element ID-based Selector

This selector can specify a unique element. The code in Listing 3 is to use this selector. Its syntax is:

"#元素 ID"

If you want to manipulate a particular element, you can set the element's ID property value, and then use the ID-based selector to specify the element to be manipulated. For example, an element with an ID of btntest in the following HTML fragment can be specified using the element ID-based selector "#btnTest".

<input type= "button" id= "btntest" value= "Test" ></input>

5 is shown below:

Figure 5. Element ID-based Selector

(online example http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=IDSelector.htm)

Selector based on element tag name

If you want to manipulate an element with the same label name (such as a hyperlink element that is represented by the label "A"), you can use a selector based on the label name. Its syntax is as follows:

"Element name"

In CSS, we can use the element tag name to do the selector. For example, the following CSS rule indicates that the font size of all links is set to 25 pixels.

a{font-size:25px;}

Using the JQuery code to implement the above CSS rules, we can use the element tag name as the selector. The code is shown in Listing 8:

Listing 8. Use element tag name as Selector
$ ("a"). each (function () {//Selector expression is "a" $ (this). CSS ("FontSize", "25px");});

Online Example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=EleNameSelector.htm

Based on CSS class name selector

JQuery also supports the class name selectors supported by CSS. Its syntax is:

". Class name"

Suppose we want to prefix the value of all the input boxes that represent the amount of the page with a currency symbol in front of it. Such a feature can be implemented with the use of class-name-based selectors: in the page, all the input box elements representing the amount of the Class property value is set to "Amount". The ability to add a currency symbol is then implemented by the following code.

Listing 9. Using CSS class masterpieces as selectors
/* Select all elements of class amount each method invokes the function specified in the method's arguments for each element that the selector matches. and takes the element as the second actual argument of a function call. */$ (". Amount"). The value of each (function (I,ele) {//setting element is its current value plus the currency symbol prefix $ (ele). Val (' ¥ ' +$ (ele). Val ());});

Online Example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=ClsNameSelector.htm

Selector based on element attributes

JQuery also supports the selector based on element attributes. Its syntax is:

"Element name [Property name = property refers to]"

For example, the following CSS rule describes setting the background color of all text boxes to yellow.

Input[type= "text"]{background-color:yellow;}

As the above page effect is implemented with JQuery code, you can use the property selector to write the appropriate code:

Listing 10. Using element attributes as selectors
$ ("Input[type=text]"). CSS (' background-color ', ' yellow ');

Online Example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=AttrSelctor.htm

DOM Object-based selectors

JQuery also supports the use of DOM objects as selectors. This selector can be very useful and convenient in some specific situations.

In the example shown in Listing 3, the listener that listens for a page load event is specified by the Initpage property of the BODY element. JQuery provides an easy way to handle the load event bindings for a page. The method is to use the Document object as a selector to pass to the $ function. Then call the Ready method to return the value to the function. Called when an event listener function is passed as a parameter to the Ready method. Therefore, the page load event bindings in the example shown in Listing 3 can be implemented in the form of JQuery code, as shown in the following code:

Listing 11: Handling page Load events using the Ready method
$ (document). Ready (initpage);//After the page is loaded, JQuery will callback Initpage

The binding of the page load event can also directly invoke the event listener function as a function parameter directly on the function. At this point, the $ function will callback the event listener after the page has finished loading (that is, the HTML document and related resource files, such as CSS, pictures, and JavaScript files, are triggered after loading). Therefore, the above code can also be written:

Listing 12: Passing functions directly to the $ function handling page Load event
$ (initpage);

Typically, such an event listener can be written as an anonymous function. As shown in the following code:

Listing 13. Using Anonymous functions
$ (function () {//This function will be called by JQuery//event-handling code} after the page has been loaded);
Other selectors

JQuery also supports other types of selectors, such as pseudo-class-based selectors, element-based hierarchical relationship selectors, and so on. For further information on selectors, you can refer to the JQuery API documentation: Http://api.juery.com/category/selectors.

Back to top of page

JQuery Architecture: Supporting plug-in mechanisms

JQuery supports extending its functionality in a way that provides plug-ins. From this perspective, when we refer to jquery, the default is the jquery kernel, which is developed and maintained by the official jquery organization. The user can develop some plugins as needed. Some common jQuery UI plugins are described later in this tutorial, and how to customize a plugin.

JQuery events: Easily implement cross-browser event handling

The Bind method can implement the binding of the event listener. Let's look at a specific example. This example implements a function like this:

When the button is clicked, a text appears below it or hides it.

Listing 14: Binding an event listener using the Bind method
When the button with ID btndetails is clicked, the following anonymous function is called by JQuery for $ ("#btnDetails"). Bind ("click", Function () {$ ("#divDetails"). Toggle ();// Show or hide the element with ID divdetails});

It can be seen from the above example (online example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=EvtBinding.htm). When the element that matches the selector is clicked, the function specified by the second argument of the Bind method is called by JQuery. The code that is responsible for showing/hiding  divDetails  The block is executed as soon as its function is called, thus achieving the desired page effect.

The syntax for the Bind method is:

Event: The name of the events to be processed. The name does not need to be prefixed to on.

Handler: Event listener, which is a function that handles browser events. This is usually an anonymous function. When the event represented by the events parameter is triggered, jquery invokes the function (called the callback) and passes the function into a jquery-customized event object. This event object was created by jQuery based on the original browser event object. JQuery does this by using a "neutral" event object to circumvent the different properties of the event object that different browsers provide for the same event. This allows us to handle events with the same code without worrying about the differences in the original event objects provided by different browsers.

Data: Represents the additional data that needs to be passed to the event listener after the event is triggered. It is passed to the event listener as the data property of the JQuery event object.

Here's a look at the concrete examples.

Using JQuery Event objects

For handling certain events, we may need to get further information about the current event from the event object.

Suppose you have an input box on the page that only allows you to enter a number. When a user enters a character that is not a numeric character, the page automatically "filters" it out, meaning that the invalid characters are not displayed in the input box. Implementing such a function requires getting the keyboard-encoded value of the key that the user is currently pressing, from the KeyPress event object that represents the user's input, in order to find the corresponding character. The code is shown in Listing 15:

Listing 15. Using JQuery Event objects
$ ("#txtVerifyCode"). Bind ("KeyPress", function (evt) {var keycode=evt.which;//gets the encoded value of the current key from the event object Var char= String.fromCharCode (keycode);//Convert the key encoding to the corresponding character if (!/\d/.test (char)) {////The current input character is not a numeric character//Preventdefault method that invokes the event object, Cancels the default behavior of the event, where the input is canceled. Evt.preventdefault ();}});

From the example above (online example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=JqEvtObj.htm), it can be seen that the specific button triggered the KeyPress The information for the event can be obtained from the corresponding property KeyCode of the jquery package jquery object. JQuery, when invoking our event listeners, passes its encapsulated event object as a unique parameter to the event listener.

Passing additional parameters to the event listener

Here's an example of passing an extra parameter to the listener.

Suppose you now have a function that displays a hint in the page, which is defined as follows:

function Showtip (msg) {$ (' #divTips '). HTML (msg);//display specific prompt content}

There are two buttons on the page that show different prompts on the page when they are clicked. So, we can write the following event listeners:

Listing 16. Getting extra data from the event object
function Showtiphandler (evt) {var data=evt.data;//get extra Parameters/* Extra parameter is a custom object that we customize as needed. Here, we assume that this object has a msg attribute. It represents the prompt message that you want to display. */var Msg=data.msg;showtip (msg);}

Then, we can use the event listener defined above when the event is bound. and define its additional parameters. The code is as follows:

Listing 17. Passing additional data to the event listener
$ (' #tip1 '). Bind (' click ', {msg: ' Chinese hint '},showtiphandler); $ (' #tip2 '). Bind (' click ', {msg: ' 中文版 tip '},showtiphandler );

From the example above (online example: http://blog.viscenthuang.info/jQuery/page/CodeDemo.htm?code=EvtObjExtraData.htm) can be seen in calling Bind The extra data specified by the method when the event listener is bound (that is, the 2nd parameter of the Bind method) can be obtained by the event listener by accessing the event object's Data property. This feature is useful when you use a unified event listener to come up with events for multiple elements.

An easy way to bind events

By using the Bind method to implement event binding, we need to specify the specific event name in the first parameter of the Bind method.

JQuery also provides some simple methods for event binding. These methods are named after the event name that you want to handle.

For example, the code in Listing 15 can be written as:

$ ("#txtVerifyCode"). KeyPress (function (evt) {//This is the event handling code});
Cancel Event Binding

If you want to cancel an event listener. You can use the Unbind method.

The following example demonstrates the cancellation of an event listener Handleclick on a button with an ID of btntest. The code is as follows:

Listing 18: Canceling event binding
$ ("#btnEvtBind"). Click (handleclick);//button btntest clicked, the Btnevtbind button no longer responds to the Click event $ ("#btnTest"). Click (function () {// Causes the Handleclick listener to no longer function as $ ("#btnEvtBind"). Unbind ("click", Handleclick);});

When you call the Unbind method, JQuery cancels all listeners that listen for the event specified by the first parameter if you do not specify a second argument. If no parameters are specified, JQuery cancels all listeners on all elements that match the selector expression.

Back to top of page

Summarize

This article explains the syntax, selectors, and event handling APIs of JQuery. These are at the heart of jquery, and are the basis for using jquery and learning the following in this series of tutorials. Although these are not difficult to master, programming is, after all, a skill, not knowledge, skills that need to be acquired through practice. Therefore, it is recommended that you take advantage of the online examples provided in this tutorial to try out your own exercises and to experience what the tutorials are doing during the practice.

Reference Learning
    • JQuery Website: http://jquery.com/
    • Google Chrome Developer Tools Official document: https://developers.google.com/chrome-developer-tools/
    • Chained syntax: http://book.51cto.com/art/201211/367093.htm
    • DeveloperWorks Web Development Zone: Extend your skills in web development with articles and tutorials dedicated to web technology.
    • DeveloperWorks Ajax Resource Center: This is a one-stop center for information about AJAX programming models, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.
    • The DeveloperWorks Web 2.0 Resource Center, a one-stop Center for Web 2.0-related information, includes a large number of Web 2.0 technical articles, tutorials, downloads, and related technical resources. You can also quickly learn about the concepts of Web 2.0 through the Web 2.0 starter section.
    • Check out the HTML5 topic for more information and trends related to HTML5.
Transferred from: http://www.ibm.com/developerworks/cn/web/1311_huangwh_jqueryhandson/

JQuery Experiment Tutorial

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.