Use jquery, Part 1: introduce desktop applications into browsers

Source: Internet
Author: User

Introduction

Jquery gradually emerged from other JavaScript libraries and became the best choice for Web developers. It quickly becomes the hope of simplifying client development and quickly and efficiently creating rich Internet applications.Program(RIA) is the first choice for programmers. With the widespread use of RIA, JavaScript libraries will be increasingly used for development. Ria is defined (loose) as an application that runs through a browser. This browser uses CSS, JavaScript, and Ajax to create a desktop-like application. The new features in Firefox, Internet Explorer, Safari, and Google Chrome are all focused on accelerating the internal JavaScript engine speed of each browser, its only purpose is to better adapt to the RIA designed by browser manufacturers for the future. These companies believe that the future web page will contain a large number of JavaScriptCodeTherefore, it is very important to develop a mature and bug-free library first.

Ajax Resource Center

Visit the Ajax Resource Center, an all-in-one center for Ajax programming model information, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.

Therefore, as Web applications continue to develop towards rich and immersive interfaces in the future, Web developers are constantly looking for tools to simplify these work. There are already several JavaScript libraries, each of which has its own advantages and disadvantages, as well as its own supporters and opponents. Here, I will not discuss which database has better features, because it has little impact on the final result. The most important thing is which database is used more-The number is the most important. Let's take a look at the Google trend chart of the four most popular JavaScript libraries below. Obviously, jquery has become the dominant JavaScript library in the past six to eight months, and this trend is still on the rise.

Figure 1. Google trend chart of common JavaScript Libraries

The job market also shows that jquery is gradually becoming the Javascript library selected by the most people. A non-scientific result from Monster.com shows that there are 113 jquery-related jobs, whereas Yui, extjs, and mootools are 67, 19, and 13 respectively.

This jquery SeriesArticleThe first article starts with exploring the jquery syntax and describes how its functions are called. The section later in this article explores the core functions of this library and how this library uses its powerful selector and filter to make Dom traversal simpler and clearer. The next article will illustrate CSS operations, Form Control, text changes, Ajax simplicity, and animation (everyone's hobby ). One of jquery's most interesting features is its plug-in architecture, which allows many developers to add new jquery functions. The last article in this article will introduce many powerful plug-ins that can be used to complete the RIA development process.

This series of articles is intended for readers who have knowledge of JavaScript, CSS, and Dom syntax. If you need to review these syntaxes before reading this series of articles, I strongly recommend the w3schools link in the reference section of this article.

Basic knowledge

Before going into interesting jquery content, let's take a look at some basic knowledge-how to install jquery and how to make it run normally. First, download the jquery library from the download section, and then link to the library like linking other external JavaScript files:

Listing 1. How to install jquery in code


<SCRIPT type = "text/JavaScript" src = "jquery. js"> </SCRIPT>

Because jquery calls or operates DOM objects, you may encounter problems when using JavaScript code to directly operate these objects before the document loads all page elements. Instead, you do not want to waitAll elementsAll loaded-all images, title ads, resolution code, and YouTube video previews-call jquery code. You can properly compromise that all elements on the page are fully loaded in the document, but before all the images, links, and presentations are complete, call jquery code in a safe and error-free way. Again, all your jquery code must be in this function on the page or in its own function. If jquery code is not in a function, it cannot be placed in JavaScript code.

Listing 2. How to call the jquery function correctly


// Incorrect
<Script language = JavaScript>
$ ("Div"). addclass ("");
</SCRIPT>

// Correct
$ (Document). Ready (function (){
$ ("Div"). addclass ("");
});

//-Or-

$ (Document). Ready (function (){
Myaddclass ();
});

Function myaddclass ()
{
$ ("Div"). addclass ("");
}

In addition, it is worth noting that a page can have any document. Ready () function, which will be called in sequence. If you are using a module to dynamically build a page, and each module has its own jquery support Code (for example, a PHP page consisting of many small PHP page fragments ), this is a good method.

One of jquery's most interesting features is "linking", which can combine a series of functions to improve readability and simplify code writing. Almost every jquery function returns a jquery object, which means that you only need to call other functions repeatedly on it to link a complete jquery command. I will compare this to the Java string class. There are several functions that return a String object, so that you can link multiple functions in the same row together:

Listing 3. jquery linking


String man = new string ("Manipulated"). touppercase (). substring (0, 5). tolowercase ();

$ ("Div"). addclass ("A"). Show (). Text ("Manipulated ");

The last thing to remember is that when jquery or any JavaScript library is used, there may be conflicts between them. In other words, when more than two libraries are used at the same time, more than one library uses the variable "$", which means that when "$" is called, the engine does not know which database to reference. A good example of this situation is the CakePHP library, which contains the built-in prototype. js. Using jquery on these pages will cause errors. To solve this problem, jquery provides a way to map the "$" variable to another variable, for example:

Listing 4. jquery solution to conflicts


J $ = jquery. noconflict ();
J $ ("Div"). addclass ("");

Select

Jquery has the ability to select and operate certain elements on the page. In a sense, it is necessary to construct an effective jquery library around these objects. Therefore, you need a method to quickly and efficiently select the elements you need to use on a common HTML page, select only the required elements (not many or many ). Jquery provides some powerful selection methods as we wish to help us find and select objects on the page. Jquery creates its own selection syntax, which is easy to understand.

(The functions used in most of the examples below will be discussed in the next article, but their functions should be intuitive and clear ).

Basically, the selection process in jquery is a huge filtering process. Every element on the page passes through this filter and it returns a matched object, or an array of matched objects that can be traversed.

The preceding three examples are the most commonly used. They use HTML tags, IDs, or class to find objects.

Html

To obtain an array of all matching HTML elements on a page, you only need to pass the HTML Tag (without parentheses) to the jquery search field. This is a fast but rough Method for searching objects. This method is useful if you want to append an attribute to a common HTML element.

Listing 5. html Selection


// This will show every <div> tag in the page. Note that it will show
// Every <div>, not the first matching, or the last matching.
// Traversing arrays is discussed later in the article.
$ ("Div"). Show ();

// This will give a red background to every <p> tag in the page.
$ ("P" ).css ("background", "# ff0000 ");

ID

Correct page settings require that each ID on the page be unique, although sometimes not (intentionally or unintentionally ). When using ID selection, jquery returns only the first matched element, because it requires you to follow the correct page design. If you need to append a tag to several elements on the same page, you should choose to use the class tag.

Listing 6. ID Selection


// This will set the innerhtml of a span element with the ID of "sampletext" to "hi ".
// Note the initial "#" in the command. This is the syntax used by jquery to search
// For IDs, and must be supported ded. If it is excluded, jquery will search for the html
// Tag instead, and with no <sampletext> tags on a page, will ultimately do
// Nothing, leading to frustrating and hard-to-find bugs (not that has ever
// Happened to me of course ).

$ ("# Sampletext" ).html ("hi ");

Class

The class is very similar to the ID. The difference is that it can be used for one or more elements on a page. Therefore, although each element on the same page has only one ID, multiple elements on the same page can still have the same class. This allows you to execute functions across multiple elements on a page, and you only need to input a class name.

Listing 7. Selecting a class


// This will create a red background on every element on the page with a class
// "Redback". notice that it doesn' t matter which HTML element this "Redback"
// Class tag is attached to. Also notice the period in the front of the query
// Term -- this is the jquery syntax for finding the class names.

$ (". Redback" ).css ("background", "# ff0000 ");

<P class = "Redback"> This is a paragraph </P>
<Div class = "Redback"> This is a big Div </div>
<Table class = "Redback"> <tr> <TD> Sample Table </TD> </tr> </table>

Merge search criteria

You can combine the above three search conditions with all the following filters in a search. By using commas (,) to separate each search condition, the search returns a set of results that match the search term.

Listing 8. Combined search


// This will hide every <p>, <span>, or <div>.
$ ("P, span, div"). Hide ();

More Filters

Although these three search parameters are undoubtedly the most commonly used in jquery, there are many other search parameters that can help you quickly find the desired elements on a page. These filters start with ":", indicating they are filters in jquery search terms. Although they can also be used as independent search conditions, they are designed to use them with the preceding three search conditions so that you can adjust the search conditions to find the specific elements you need.

Listing 9. More Filters


// This will hide every <p> tag on a page
$ ("P"). Hide ();

// This will hide the first element on a page, no matter its HTML Tag
$ (": First"). Hide ();

// Notice how these can be used in combination to provide more fine tuning
// Search criteria. This will hide only the first <p> tag on a given page.
$ ("P: First"). Hide ();

Multiple filters can be used as search elements. Although I have not listed all the filters here (this is a task on the API page), some of them are very convenient in processing pages and search elements.

MeSetFocus on some important filters in the selection package. They areFormElement filter. Today's rich Internet applications focus on forms and elements (text fields, buttons, check boxes, and single-choice buttons) that collect and transmit information from the server, or collect and transmit information to the server. Because of their important roles in RIA, these filters are very important in today's Web applications when dealing with jquery.

These filters work in the same way as the filters described earlier, and start with ":", indicating they are filters. They can also be used with other search filters to refine search criteria. Therefore, a ": Text" search filter returns each text field on the page, while a ". largefont: Text "search filters only return text fields that are part of the" largefont "class on the page. This allows further refinement and operation of form elements.

The form filter also includes every attribute of the element. Understanding this knowledge is good for developers. Therefore, search filters such as ": checked", ": Disabled", and ": Selected" further refine the search conditions for specific searches.

Traversal

Now you have learned how to search and filter all elements on the page. Next, you need an efficient method to traverse the results and further process the elements. Naturally, jquery provides several methods to traverse search results.

The first and most common Traversal method is the each () function. This is the same as the "For Loop" function. it traverses each element and increments the Element Through iteration. In addition, the reference of each element in the loop can be implemented through "this" (for general JavaScript syntax) or $ (this) (For jquery commands.

Let's take a look at the following example.

Listing 10. Each loop


// Will loop through each <p> tag on the page. Notice the use of
// Inline function here -- this is analogous with the anonymous classes in Java.
// You can either call a separate function, or write an inline function like this.

VaR increment = 1;
$ ("P"). Each (function (){

// Now add a paragraph count in front of each of them. Notice how we use
// $ (This) variable to reference each of the paragraph elements individually.

$ (This). Text (increment + "." + $ (this). Text ());
Increment ++;
});

Because the search results are stored in an array, you certainly want the function to traverse the array, just like processing otherProgramming Language. Therefore, to find the length of a given search result, you can call $ (). length on the array. Listing 11 shows more array traversal functions, which can be used for Array traversal in other programming languages.

Listing 11. Other array Functions


// The eq () function lets you reference an element in the array directly.
// In this case, it will get the 3rd paragraph (0 referenced of course) and hide it
$ ("P"). eq (2). Hide ();

// The slice () function lets you input a start and an end index in the array,
// Create a subset of the array. This will hide the 3rd through 5th paragraphs on
// Page
$ ("P"). Slice (2, 5). Hide ();

In addition to these array traversal functions, jquery also provides functions that allow you to find elements nested around search words. Why is this useful? For example, we often need to embed a text Tag next to an image or an error message next to a form element. You can use these commands to find a specific form element. Then, by placing the form Element in the next element (span tag), the error message is placed directly next to the form element. Listing 12 shows an example of this design:

Listing 12. Example of the next () function


<Input type = text class = validate> <span> </span>

Function validateform ()
{
$ (". Validate: Text"). Each (function (){
If ($ (this). Val () = "")
// We'll loop through each textfield on the page with a class of "Validate"
// And if they are blank, we will put text in the <span> immediately afterwards
// With the error message.

Certificate (this).next().html ("this field cannot be blank ");
});
}

Comprehensive knowledge

To learn how to work with the above knowledge, you can view the sample applications included in this article (see the references section ).

This section briefly introduces the sample application. I will use this sample application in all articles in this series, because it uses a large number of different jquery examples, and almost everyone is familiar with this application-a rich Internet application that processes Web mail. This example application is a simple mail client that uses jquery to give users the feeling that the e-mail client is very similar to a desktop application. At the end of the last article, you will understand how this simple application creates this feeling for users and how easy it is to implement this function using jquery.

This article focuses on the "select all"/"deselect all" check boxes, which appear at the top of the left column of the web mail table (highlighted below. When this check box is selected, it selects each check box for this column; when this check box is deselected, it removes all check boxes for this column.

Figure 2. Select All check box

List 13. Comprehensive knowledge


<! -- The first step is creating the Select All checkbox itself.
We give it a unique ID on the page -->

<Input type = checkbox id = selectall>

<! -- The next step is giving each of the rows their own checkbox.
We put each row's checkbox into the 'selectable' class, since there can be rows,
And we want each of the rows 'checkboxes to have the same behavior. -->

<Input type = checkbox class = selectable>

<! -- The final step is bringing it all together with some jquery code. -->

// Remember that all jquery setup code must be in this document. Ready () function,
// Or contained within its own function in order to function correctly.

$ (Document). Ready (function (){
// We use the jquery selection syntax to find the selectall checkbox on the page
// (Note the '# 'which signifies ID), and we tell jquery to call the selectall ()
// Function every time someone clicks on the checkbox (we'll get to events in
// Articure article ).

$ ("# Selectall"). Click (selectall );
});

// This function will get called every time someone clicks on the selectall checkbox
Function selectall ()
{
// This line determines if the selectall checkbox is checked or not. The ATTR ()
// Function, discussed in a future article, simply returns an attribute on
// Given object. In this case, it returns a Boolean if true, or an undefined if
// It's not checked.

VaR checked = $ ("# selectall"). ATTR ("checked ");

// Now we use the jquery selection syntax to find all the checkboxes on the page
// With the selectable class added to them (each row's checkbox). We get an array
// Of results back from this selection, and we can iterate through them using
// Each () function, lew.us work with each result one at a time. Inside
// Each () function, we can use the $ (this) variable to reference each individual
// Result. Thus, inside each loop, it finds the value of each checkbox and matches
// It To The selectall checkbox.

$ (". Selectable"). Each (function (){
VaR subchecked = $ (this). ATTR ("checked ");
If (subchecked! = Checked)
$ (This). Click ();
});
}

Conclusion

Jquery is a Web application developmentCommunityAnd it becomes more important as rich Internet applications become increasingly popular. As many companies migrate internal applications online and move everyday desktop applications (including word processors and workbooks) online ), javascript libraries that simplify development and implement cross-platform support will become a required technology for designing the application architecture.

This first article on jquery introduces jquery syntax, how to correctly use jquery in your own JavaScript code, and how to avoid conflicts when using other libraries in combination. In addition, this article also introduces the jquery search and selection syntax, which is the basis of other jquery functions. It allows you to quickly and easily find the required page elements. The article also explains how to traverse search results so that you can process elements one by one. These two aspects of jquery are the basis of the next article in this series and also the basis of all jquery code.

Finally, we introduced a demo application, which is a rich client web mail application. In this article, you have created the Select All/deselect all check box through the learned jquery knowledge, and you can create a widget that is very common on many web sites with only a few lines of code.

The next article will add some interactions to this sample Web application. You will learn how to handle page events (click an element, click a button, and select a combo box), how to get a value from the elements on the page, and how to modify the standard CSS on the page to change the color, layout, without re-loading the page.

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.