Ajax framework jquery usage

Source: Internet
Author: User
Tags api manual
Query 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 perform simple operations on your web page. Composition File, process events, implement special effects, and add Ajax interactions to web pages.

It has the following features:
1,CodeConcise, easy to understand, fast to learn, 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 users. It is also suitable for commercial development. It can be said that jquery is suitable for any JavaScript Application and can be used for different web applications.Program.
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']})
// 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']});

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']})
// 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);
}< br> JSON data can also be processed, as shown in
$. 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.
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 defaults and options, and return the Merged Results to setting without overwriting the default content.
multiple parameters (merging multiple parameters and returning results)
$. Map (array, FN): array ing. Save the items in an array (after conversion) to another new array and return the new array.
example:
var temparr = $. map ([, 2], function (I) {return I + 4 ;});
temparr content, 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.
E. g.: $. merge ([, 2], [, 4]) // Returns [, 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.
in many cases, we define $ (ID) method To get an element, or some other JS class libraries such as prototype also define the $ method. If these contents are put together at the same time, it will cause a variable method definition conflict, jquery provides a dedicated solution to this problem.
the jquery. noconflict (); Method in jquery can be used to assign control of the variable $ to the first library implementing it or the previously defined $ method. 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 ").
example:
jquery. noconflict ();
// start to use 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.