Using jquery to introduce desktop applications into the browser _jquery

Source: Internet
Author: User
Tags html tags unique id jquery library
With the extensive use of RIA, JavaScript libraries will be used more and more to assist development. RIA is defined (loosely) as a browser-run application that uses Css/javascript/ajax to create a similar appearance to a desktop application. The new features in Firefox, Internet Explorer and Safari's latest releases, and the latest version of Google's newest Chrome browser, are focused on speeding up the internal JavaScript engine of each browser, Its sole purpose is to be more adapted to the RIA that the browser manufacturer designs for the future. These companies think that future Web pages will contain a lot of JavaScript code, so it's important to first develop a mature, bug-free library.

Therefore, as future Web applications continue toward the rich and immersive interface, Web developers are constantly looking for tools to streamline these efforts. There are now a few JavaScript libraries, each with its own pros and cons, as well as its own supporters and opponents. Here, I don't discuss which library features are better because it doesn't have much impact on the end result. The most important thing is which library to use more-the quantity is the most important. Take a look at the Google trend chart for the 4 most popular JavaScript libraries below. It is clear that in the last 6-8 months, JQuery has become the dominant JavaScript library, and this trend is still rising.

Figure 1. Google Trend Chart for common JavaScript libraries

The job market has also shown that jQuery is gradually rising to the top of the JavaScript Library of choice. A monster.com result of the study shows that there are 113 positions associated with jQuery, while YUI, ExtJS and MooTools are 67, 19 and 13 respectively.

The first of this jquery series begins with exploring the jquery syntax, and also understands how its functions are invoked. The later sections of this article explore the core functions of the library, and how the library uses its powerful selectors and filters to make DOM traversal easier and clearer. The next article will explain CSS operations, form control, text changes, Ajax simplicity, and animations (everyone's hobby). One of the most interesting features of JQuery is its plug-in architecture, which allows many developers to add new jquery functionality. The last article in this article will introduce a number of powerful plug-ins that can be used to complete the RIA development process.

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

Basic knowledge

Before delving into the interesting jquery content, let's take a look at some basics-how to install jQuery, and how to make it work properly, and so on. Download the JQuery library from the download section first, and then link to the library like any other external JavaScript file:


Listing 1. How to install JQuery in your code
<script type= "Text/javascript" src= "Jquery.js" ></script>

Because JQuery invokes or operates DOM objects, it is problematic to use JavaScript code to manipulate these objects directly before the document loads all the page elements. Instead, you don't want to wait for all the elements on the page to load-all images, banner ads, parsing code, and YouTube video previews-to start calling JQuery code. You can compromise the JQuery code in a secure, error-free manner before the document completely loads all the elements on the page, but until all the images, links, and rendering have been completed. Again, all your jQuery code must be in this function on the page, or in its own function. If the JQuery code is not in a function, you cannot place its code in JavaScript code.


Listing 2. How to call the JQuery function correctly
Incorrect
<script language=javascript>
 $ ("div"). addclass ("a");
</script>

//correct
$ (document). Ready (function () {
 $ ("div"). addclass ("a");
 });

-Or-

$ (document). Ready (function () {
 myaddclass ();
 });

function Myaddclass ()
{
 $ ("div"). addclass ("a");

In addition, there is a noteworthy place: a page can have any document.ready () functions, they will be called in turn. 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 made up of a number of very small PHP page fragments), this is a good way to do it.

One of the most interesting features of JQuery is "linking", which can centralize a series of functions, improve readability, and simplify coding. Almost every jquery function returns a JQuery object, which means you can link a complete jquery command by simply calling other functions over and over again. I compare this to the Java string class, where several functions return a string object that allows you to link multiple functions on the same line:


Listing 3. The link nature of JQuery
String man = new String ("manipulated"). toUpperCase (). substring (0,5). toLowerCase ();

$ ("div"). addclass ("a"). Show (). Text ("manipulated");

The last thing to remember is that when you use JQuery or any JavaScript library, there is a potential conflict between them. In other words, when more than two libraries are used at the same time, more than one library uses the variable "$" at the same time, which means that the engine will not know which library to reference when making a "$" call. A good example of this is the cake library, which contains built-in prototype.js. Using JQuery on these pages will result in an error. To solve this problem, JQuery provides a way to map the "$" variable to another variable, for example:


Listing 4. JQuery's approach to conflict resolution
j$ = Jquery.noconflict ();
j$ ("div"). addclass ("a");

Choose

The root of jQuery is its ability to select and manipulate certain elements on the page. In a sense, there is a need to surround these objects to build a valid JQuery library. So, in the face of a lot of options available on a normal HTML page, you need a way to quickly and efficiently select the elements you need to use on the page, and select only the elements you need (no more or less). JQuery provides a number of powerful options as we wish, helping us find and select objects on the page. JQuery creates its own selection syntax, and this syntax is easy to master.

(The functions used by most of the following examples will remain discussed in the next article, but their functionality should be straightforward).

Essentially, the selection process in JQuery is a huge filtering process, with every element on the page passing through the filter, which returns a matching object, or an array of matched objects that can be traversed.

The first 3 examples are the most common. They look for objects through HTML tags, ids, or CLASS.

Html

To get an array of all the matching HTML elements in a page, you only need to pass the HTML tags (without parentheses) to the JQuery search field. This is a "quick but rough" way to find objects. This is useful if you want to attach a property to a generic HTML element.


Listing 5. HTML selection
 
This is the every <div> tag in the page. Note that it would show 
//Every <div>, not the The "the", or the last matching. 
Traversing Arrays is discussed later in the article.
$ ("div"). Show ();

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

Id

The correct page setup requires that each ID on the page be unique, although sometimes it is not (intentionally or unintentionally). When using ID selection, JQuery returns only the first matching element because it requires you to follow the correct page design. If you need to attach a tag to several elements on the same page, you should choose to use the CLASS tag.


Listing 6. ID selection
 
This is set the InnerHTML of a SPAN element with the ID of ' sampletext ' to ' Hi '. 
The initial "#" in the command. This is the syntax used by jQuery to search 
//For IDs, and must be included.  If It is excluded, JQuery would search for the HTML
//tag instead, and with no <sampleText> tags on a page, would Ultimately do
//No, leading to frustrating and hard-to-find bugs (not so, has ever 
//happened to me Of course).

$ ("#sampleText"). HTML ("Hi");

CLASS

The CLASS is very similar to the ID, but the difference is that it can be used for one or more elements on a page. As a result, multiple elements on the same page can still have the same CLASS, although only one ID is limited to each element of the same page. This allows you to execute functions across multiple elements on a single page, and simply pass in a CLASS name.


Listing 7. CLASS selection
 
This would create a red background on every element in the page with a CLASS of 
//"Redback". Notice that it doesn ' t matter which the HTML element this ' redback ' 
//CLASS tag are 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 are a big >this
<table class= "Redback" ><tr><td>sample table</td></tr></table>
           

Merge search criteria

You can combine the above 3 search criteria with all of the following filters in one search. By separating each search condition by using, the search returns a set of results that match the search terms.


Listing 8. Merge Search
 
This'll hide every <p>, <span>, or <div>.
$ ("p, span, div"). Hide ();

More Filters

Although these 3 search parameters are undoubtedly the most common in jQuery, there are many other search parameters that can help you quickly find the elements you need on a page. These filters begin with ":" to indicate that they are filters in the JQuery search term. Although they can also be used as separate search criteria, they are designed to work with the above 3 search criteria, allowing you to adjust your search criteria to find the specific elements you need.


listing 9. More Filters
 
This'll hide every <p> tag on a page
$ ("P"). Hide ();

This would hide the the "a" page and no matter its HTML tag
$ (": a"). Hide ();

Notice how this can be used into combination to provide more fine tuning of 
//search criteria. This would hide only the <p> tag on a given page.
$ ("P:first"). Hide ();

You can use more than one filter as a search element. While I'm not listing all of the filters here (this is the task of the API page), some of these filters are handy for working with pages and search elements.

I'll focus on some of the most important filters in the Selection package, which are the form element filters. Today's rich Internet applications are more concerned with forms and the elements contained therein (text fields, buttons, check boxes, radio buttons, and so on) that collect and transmit information from the server, or gather information and transfer to the server. Because of their important role in RIA, these filters are important in today's WEB applications when working with JQuery.

These filters work the same way as the filters described earlier and also begin with ":" to indicate that they are filters. Similarly, they can be used with other search filters to refine search conditions. Therefore, a ": text" search filter returns each text field on the page, and a ". Largefont:text" search filter returns only the text fields on the page that are part of the "Largefont" class. This allows you to further refine and manipulate the form elements.

The form filter also includes each attribute of the element, and understanding this knowledge is beneficial to the developer. Search filters such as ": Checked", ":d isabled" and ": Selected" will further refine search conditions for specific searches.

Traverse

Now that you've learned how to search for and filter all the elements on a page, you need an efficient way to traverse the results and process the elements further. Naturally, JQuery provides several ways to traverse search results.

The first and most commonly used traversal method is the each () function. This is the same as the "for loop" function, traversing each element and incrementing the element by iterating through the iteration. In addition, a reference to 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

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

var increment = 1;
$ ("P"). each (the function () {

 //Now add a paragraph count in front of each of them. Notice How do we use the
 //$ (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 definitely want the function to traverse the array just as you would a data object in another programming language. Therefore, to find the length of a given search result, you can call $ () on the array. length. Listing 11 shows more array traversal functions that can be applied to array traversal in other programming languages.


listing 11. Other array Functions

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

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

In addition to these array traversal functions, JQuery provides functions that allow you to look up elements that are nested around search terms. Why is this useful? For example, we often need to embed a text label next to the picture, or embed an error message next to the form element. Use these commands to find a specific FORM element, and then place the error message directly next to the form element by placing the form element in the next element (span tag). Listing 12 shows an example of this design:


Listing 12. Example next () function

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

function validateform ()
{
 $ (". Validate:text "). each (function () {
 if ($ (). val () =" ")
 //We ll loop through each TextField on the page with a CL Ass of "Validate"
 //And if they are blank, we'll put text in the <span> immediately afterwards
 //with th e error message.

  $ (this). Next (). HTML (' This field cannot is blank ');
}

The knowledge that is learned in general

To learn how to use these knowledge together, you can view the sample applications included in this article (see Resources section).

Here's a quick introduction to the sample application. I'll use this sample application in all the articles in this series because it uses a lot of different jQuery samples, and almost everyone is familiar with the application-a rich Internet application that handles Web mail. The sample application is a Simple mail client that leverages JQuery to give the user the impression that the e-mail client is very similar to a desktop application. At the end of the last article, you will see how this simple application creates this feeling for the user and how simple it is to use JQuery to implement this functionality.

The focus of this article is the Select All/deselect all check box, which appears at the top of the left column of the Web Mail table (highlighted below). When the check box is selected, it selects each check box for that column, and when the check box is deselected, it cancels all the check boxes for that column.


Figure 2. Select all check box


Listing 13. The knowledge that is learned in general

 
<!--the Creating the Select all checkbox itself. We give it a unique ID on the page--> <input type=checkbox id=selectall> <!--the "next" is giving each
The rows their own checkbox. We put each row's checkbox into the ' selectable ' class, since there can is many rows, and we want each of the rows ' checkb Oxes to have the same behavior. --> <input Type=checkbox class=selectable> <!--The final step are bringing it all together with some jQuery Code. -->//Remember so all JQuery Setup code must is 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 of the SelectAll checkbox on the page// The ' # ' which signifies ID), and we tell JQuery to call the SelectAll ()//function every time someone clicks on the CHEC

 Kbox (We ll get to Events in A//future article). $ ("#selectall"). Click (SelectAll);
}); This function is called every time someone clicks on the SelectAll checkbox function SelectAll () {/ Determines if the SelectAll checkbox is checked or not. The attr ()//function, discussed in a future article, simply returns an attribute on the//given object.

 In this case, it returns a Boolean if true, or a 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 th EM (each row ' s checkbox). We get a array//of results back to this selection, and we can iterate through them using the '//each () function, le Tting us work with a. Inside the//each () function, we can use the $ (this) variable to reference per 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 very popular JavaScript library in the WEB application development community and will become more important as rich Internet applications become more popular. Since many companies migrate in-house applications online and move daily desktop applications (including word processors and spreadsheets) online, simplifying the development and implementation of Cross-platform support for JavaScript libraries will be a necessary technology for designing application architectures.

The first installment of this series on jquery describes the jquery syntax, how to use jquery correctly in your own JavaScript code, and how to avoid conflicts when using other libraries in conjunction. In addition, this article introduces the jquery search and selection syntax, which are the basis for other jquery features. It allows you to quickly and easily find the page elements that you want. The article also discusses how to traverse search results, allowing you to process elements individually. These two aspects of jquery are the foundation of the next article in this series, as well as the basis of all jquery code.

Finally, a demo application is introduced, which is a rich client Web mail application. In this article, you create the Select all/deselect all check box with the knowledge of jQuery, and you can create a widget that is very common on many Web sites with just a few lines of code.

The next article will add some interaction to this sample WEB application. You'll learn how to handle page events (click Elements, button clicks, combo box selections, and so on), get values from elements on the page, and modify the standard CSS on the page to change colors, layouts, and so on without reloading 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.