A very popular ajax framework, JQuery

Source: Internet
Author: User
Tags api manual jquery library

 

Jquery library. You can find the latest download here. This Guide provides a package containing the instance for download.
Download: jquery starterkit
(Translator keel Note: You must download this package. It is definitely not feasible to read articles without practice .)
Download and decompress the files. Then, use your most recent editor to open starterkit.html and custom. js. (Translator keel Note: all examples are written using these two examples. m.js writes the jquerycode and starterkit.html observes the effect. editplus is recommended)
Now we have made all preparations for this famous "Hello World" example.

Hello jquery, before doing everything, we need jquery to read and process the document's Dom, and it must start to execute the event as soon as possible after Dom loading. Therefore, we use a ready event as the start to process HTML documents. look at the M m we opened. JS file, which is ready:

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

Put a simple alert event and wait for the Dom to load it. So we make the task a little more complicated: an alert is displayed when you click any link.

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

This will trigger the "Hello World" prompt when you click a link on the page.
(Translator keel Note: follow this code to modify custom.js and save it. Then, use a browser to open starterkit.html to observe the effect .)
Let's take a look at the meaning of these changes. $ ("A") is a jquery selector. Here, it selects all the tags (translator keel Note: <A> </a> ), $ is an alias for jquery "class". Therefore, $ () constructs a new jquery object ). The function click () is a method of this jquery object. It binds a click event to all selected tags (all a tags here ), the provided alert method is executed when the event is triggered.
Here is a code for similar functions:

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

Obviously, jQuery does not need to write onclick events on each a tag, so we have a neat structure document (HTML) and a behavior document (JS ), it achieves the goal of separating structure and behavior, just as we pursue with CSS.
Next we will learn more about selectors and events.
<Script type = "text/javascript" src = "style/lib/jquery. js"> </script>
<Script type = "text/javascript" src = "style/lib/jquery. dimensions. js"> </script>
<Script type = "text/javascript" src = "style/lib/jquery. corner-min.js"> </script>
<Script type = "text/javascript" src = "style/jqueryapi. js "> </script> with the rapid development and dissemination of WEB2.0 and ajax ideas on the Internet, some excellent Js frameworks have emerged one after another, among them, Prototype, YUI, jQuery, mootools, Bindows, and JSVM frameworks in China are well-known, by applying these JS frameworks to our projects, programmers can be freed from complicated JS applications in design and writing, and focus on functional requirements rather than implementation details, this improves the project development speed.
JQuery is another excellent Javascript framework after prototype. It was created by John Resig in early 2006 and helps simplify JavaScript and Ajax programming. Someone uses this analogy to compare prototype and jQuery: prototype is like Java, while jQuery is like ruby. it is a simple, fast, and flexible JavaScript framework that allows you to easily operate documents, process events, implement special effects, and add Ajax interactions to Web pages on your webpage.

It has the following features:
1. concise code, easy-to-understand semantics, fast learning, and rich documentation.
2. jQuery is a lightweight script with very small code. The latest JavaScript package is only about 20 kb.
3. jQuery supports CSS1-CSS3 and basic xPath.
4. jQuery supports cross-browser browsers, including IE 6.0 +, FF 1.5 +, Safari 2.0 +, and Opera 9.0 +.
5. Other functions can be easily extended for jQuery.
6. JavaScript code and HTML code can be completely separated to facilitate code maintenance and modification.
7. Rich plug-ins. In addition to some special effects of jQuery, you can use plug-ins to implement more functions, such as form verification, tab navigation, drag-and-drop effects, table sorting, and DataGrid, tree menu, image effects, and ajax upload.

JQuery design will change the way you write JavaScript code, reduce the complexity of learning to use JavaScript to operate webpages, and improve the JS development efficiency of webpages, no matter for beginners of JS or senior experts, jQuery will be your first choice.
JQuery is suitable for designers, developers, and other good people. It is also suitable for commercial development. It can be said that jQuery is suitable for any JavaScript Application and can be used in different Web applications.
Official site: http://jquery.com/Chinese site: http://jquery.org.cn/

1.2 Purpose
By studying this document, you can have a simple understanding of jQuery, understand the differences between JQuery and other JS frameworks, and master the common syntax, usage skills, and precautions of jQuery.

Ii. Usage
Introduce the JQuery js file on the page that requires JQuery.
Example: <script type = "text/javascript" src = "js/jquery. js"> </script>
After the introduction, you can use the syntax provided by jQuery anywhere on the page.

Iii. Learning tutorials and references
See jQuery Chinese API manual and http://jquery.org.cn/visual/cn/index.xml
We recommend two good jquery Tutorials: jQuery's starting point tutorial and jQuery's simplified Ajax development.


Iv. Syntax summary and precautions

1. Reference of page elements
The $ () referenced element of jquery includes methods such as id, class, element name, element hierarchy, dom or xpath conditions, and the returned object is a jquery object (set object ), you cannot directly call methods defined by the dom.

2. Conversion between jQuery objects and dom objects
Only jquery objects can use methods defined by jquery. Pay attention to the differences between dom objects and jquery objects. When calling methods, pay attention to dom objects or jquery objects.
Common dom objects can be converted to jquery objects through $.
For example, $ (document. getElementById ("msg") is a jquery object. You can use the jquery method.
Because the jquery object itself is a set. Therefore, if a jquery object is to be converted to a dom object, You must retrieve one of them. Generally, you can retrieve it through indexes.
For example: $ ("# msg") [0], $ ("div "). eq (1) [0], $ ("div "). get () [1], $ ("td") [5] are all dom objects. You can use methods in dom, but you cannot use Jquery methods.
The following statements are correct:
$ ("# Msg" cmd.html ();
$ ("# Msg") [0]. innerHTML;
$ ("# Msg"). eq (0) [0]. innerHTML;
$ ("# Msg"). get (0). innerHTML;

3. How to obtain a certain entry of the jQuery set
For the obtained element set, you can use the eq or get (n) method or index number to obtain one of the items (specified by the index). Note that the returned eq is a jquery object, get (n) and index return dom element objects. Jquery objects can only use jquery methods, while dom objects can only use dom methods. For example, you need to obtain the content of the third <div> element. There are two methods:
$ ("Div" ).eq(2).html (); // call the jquery object Method
$ ("Div"). get (2). innerHTML; // call the dom method attribute

4. Implement set and get for the same function
Many methods in Jquery are like this, mainly including the following:
$ ("# Msg" ).html (); // return the html content of the element node whose id is msg.
$ ("# Msg" cmd.html ("<B> new content </B> ");
// Write "<B> new content </B>" as an html string to the element node content with the id of msg. The new content in bold is displayed on the page.

$ ("# MSG"). Text (); // return the text content of the element node whose ID is MSG.
$ ("# MSG"). Text ("<B> new content </B> ");
// Write "<B> new content </B>" as a common text string to the element node content with the ID of MSG. The page displays <B> new content </B>

$ ("# MSG"). Height (); // returns the height of the element whose ID is MSG.
$ ("# MSG"). Height ("300"); // set the height of the element whose ID is MSG to 300
$ ("# MSG"). Width (); // return the width of the element whose ID is msg
$ ("# MSG"). Width ("300"); // set the width of the element whose ID is MSG to 300

$ ("Input"). Val ("); // return the value of the input box of the form.
$ ("Input"). Val ("test"); // set the value of the form input box to test

$ ("# MSG"). Click (); // trigger the click event of an element whose ID is msg
$ ("# MSG"). Click (FN); // click an event to add a function for an element whose ID is msg
Similarly, blur, focus, select, and submit events can all have two call methods.

5. Set Processing
For the set content returned by jquery, we do not need to iterate through it and process each object separately. jquery has provided us with a very convenient way to process the set.
There are two forms:
$ ("P "). each (function (I) {This. style. color = ['# f00',' #0f0 ',' # 00f'] [I]})
// Set different font colors for P elements whose indexes are 0, 1 and 2 respectively.

$ ("TR"). Each (function (I) {This. style. backgroundcolor = ['# CCC', '# fff'] [I % 2]})
// Implement the Color Changing Effect of the row separation of the table

$ ("P" ).click(function(){alert(((this).html ())})
// Adds a click event for each P element. Click a P element to bring up its content.

6. Expand the functions we need
$. Extend ({
Min: function (a, B) {return a <B? A: B ;},
MAX: function (a, B) {return A> B? A: B ;}
}); // Added the min and Max methods for jquery.
Use an extended method (called by "$. Method Name ):
Alert ("A = 10, B = 20, max =" + $. Max (10, 20) + ", min =" + $. Min (10, 20 ));

7. method-based writing
The so-called continuous writing means that different methods can be called continuously for a jquery object.
For example:
$ ("P" ).click(function(){alert(((this).html ())})
. Mouseover (function () {alert ('mouse over event ')})
. Each (function (I) {This. style. Color = ['# f00',' #0f0 ',' # 00f'] [I]});

8. Style of operation elements
It mainly includes the following methods:
$ ("# MSG" ).css ("background"); // return the background color of the element.
$ ("# MSG" ).css ("background", "# CCC") // set the element background to Gray.
$ ("# MSG"). Height (300); $ ("# MSG"). Width ("200"); // set the width and height
$ ("# MSG" ).css ({color: "red", Background: "blue"}); // set the style as a name-Value Pair
$ ("# MSG"). addclass ("select"); // Add a class named select for the element
$ ("# MSG"). removeclass ("select"); // Delete the class whose element name is select
$ ("# MSG"). toggleclass ("select"); // Delete (ADD) the Select class if it exists (does not exist)

9. Complete event handling functions
Jquery already provides various event handling methods. Instead of Directly Writing events on HTML elements, we can directly add events to objects obtained through jquery.
For example:
$ ("# Msg"). click (function () {alert ("good")}) // added a click event for the element
$ ("P "). click (function (I) {this. style. color = ['# f00',' #0f0 ',' # 00f'] [I]})
// Set different processing for three p-element click events
Several custom events in jquery:
(1) hover (fn1, fn2): a method that imitates a hover event (move the mouse over an object and remove it. When you move the cursor over a matching element, the specified first function is triggered. When you move the cursor out of this element, the specified second function is triggered.
// When you place the cursor over a row of the table, set the class to over and the class to out when you leave the table.
$ ("Tr"). hover (function (){
$ (This). addClass ("over ");
},
Function (){
$ (This). addClass ("out ");
});
(2) ready (fn): binds a function to be executed when the DOM is loaded and can be queried and manipulated.
$ (Document). ready (function () {alert ("Load Success ")})
// After the page is loaded, the message "Load Success" is displayed, which is equivalent to an onload event. Equivalent to $ (fn)
(3) toggle (evenFn, oddFn): switches the function to be called each time you click. If a matching element is clicked, the specified first function is triggered. When the same element is clicked again, the specified second function is triggered. The subsequent clicks repeatedly call the two functions.
// Add or delete a class named selected every time you click it.
$ ("P"). toggle (function (){
$ (This). addClass ("selected ");
}, Function (){
$ (This). removeClass ("selected ");
});
(4) trigger (eventtype): triggers an event on each matching element.
For example:
$ ("P"). trigger ("click"); // triggers the click event of all p elements
(5) bind (eventtype, fn) and unbind (eventtype): bind and unbind events
Deletes a bound event from each matching element.
For example:
$ ("P "). bind ("click", function () {alert ($ (this ). text () ;}); // Add a click event for each p element
$ ("P"). unbind (); // delete all events on all p elements
$ ("P"). unbind ("click") // Delete the click Event on all p elements

10. Some practical special effects
The toggle () and slidetoggle () methods provide the status switching function.
For example, the toggle () method includes the hide () and show () methods.
The slideToggle () method includes the slideDown () and slideUp methods.

11. Several useful jQuery Methods
$. Browser. browser type: Check the browser type. Valid parameters: safari, opera, msie, and mozilla. If ie: $. browser. isie is detected, true is returned for ie.
$. Each (obj, fn): A common iteration function. It can be used to iterate objects and arrays (instead of loops) in an approximate way ).
For example
$. Each ([0, 1, 2], function (I, n) {alert ("Item #" + I + ":" + n );});
It is equivalent:
Var tempArr = [0, 1, 2];
For (var I = 0; I <tempArr. length; I ++ ){
Alert ("Item #" + I + ":" + tempArr [I]);
}
Json data can also be processed, such
$. Each ({name: "John", lang: "JS"}, function (I, n) {alert ("Name:" + I + ", Value: "+ n );});
Result:
Name: name, Value: John
Name: lang, Value: JS
$. Extend (target, prop1, propN): expands an object with one or more other objects and returns the extended object. This is an inheritance method implemented by jquery.
For example:
$. Extend (settings, options );
// Merge settings and options, and return the Merged Results to settings, which is equivalent to inheriting setting and saving the inherited results in setting.
Var settings = $. extend ({}, defaults, options );
// Merge ults and options, and return the merged result to setting without overwriting the default content.
There can be multiple parameters (merging multiple parameters and returning them)
$. Map (array, fn): array ing. Save the items in an array (after conversion) to another new array and return the new array.
For example:
Var tempArr = $. map ([0, 1, 2], function (I) {return I + 4 ;});
TempArr content: [4, 5, 6]
Var tempArr = $. map ([0, 1, 2], function (I) {return I> 0? I + 1: null ;});
TempArr content: [2, 3]
$. Merge (arr1, arr2): merges two arrays and deletes repeated items.
For example: $. merge ([, 2], [, 4]) // return [, 4]
$. Trim (str): removes spaces at both ends of a string.
For example: $. trim ("hello, how are you? "); // Return" hello, how are you? "

12. Resolve conflicts between custom methods or other class libraries and jQuery
Most of the time, we define the $ (ID) method to obtain an element, or some other JS class libraries such as prototype define the $ method, if these contents are put together at the same time, the variable method definition conflict will occur. jquery provides a dedicated method to solve this problem.
Use the jquery. noconflict (); Method in jquery to assign control of the variable $ to the first library or the previously customized $ method to implement it. When jquery is applied, you only need to replace all $ with jquery. For example, the original reference object method $ ("# MSG") is changed to jquery ("# MSG ").
For example:
Jquery. noconflict ();
// Start using jquery
Jquery ("Div P"). Hide ();
// Use $ () for other libraries ()
$ ("Content"). style. Display = 'none ';

 

 

Related Article

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.