A summary of tips for using jquery

Source: Internet
Author: User
Tags api manual xpath

First, Introduction

1.1. Overview
With the rapid development of WEB2.0 and Ajax ideas on the Internet, there have been some excellent JS frames, among them the famous prototype, YUI, JQuery, MooTools, Bindows and the domestic JSVM framework, etc. By applying these JS frameworks to our projects, programmers can be freed from designing and writing complex JS applications, turning the focus to functional requirements rather than implementation details, thus increasing the speed of project development.
jquery is another excellent JavaScript framework following prototype. It was created by John Resig in early 2006 to help simplify JavaScript™ and Ajax programming. Some people use such a metaphor to compare prototype and jquery:prototype like Java, and jquery is like Ruby. It's a simple, fast and flexible JavaScript framework that allows you to easily manipulate documents, handle events, implement effects, and add Ajax interactivity to your Web pages on your Web pages.

It has some of the following features:
1. Concise code, easy to understand, quick to learn and rich in documentation.
2, jquery is a lightweight script, its code is very small, the latest version of the JavaScript package only about 20K.
3, jquery supports CSS1-CSS3, and basic XPath.
4, jquery is cross-browser, it supports the browser including IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+.
5. It is easy to extend other functions for jquery.
6, the JS code and HTML code can be completely separated, easy to code and maintenance and modification.
7, plug-in rich, in addition to the jquery itself with some special effects, can be implemented through plug-ins to achieve more features, such as Form validation, tab navigation, drag and drop effects, table sorting, DataGrid, tree menu, image effects and Ajax uploads.

jquery design will change the way you write JavaScript code, reduce the complexity of your learning to use JS Web pages, improve the efficiency of Web page JS development, whether for JS beginners or senior experts, jquery will be your first choice.
jquery is suitable for designers, developers, and those who are good for business development, and 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, we can have a simple understanding of jquery, and clearly understand the differences between jquery and other JS frameworks, and master the common syntax, usage skills, and considerations of jquery.

Ii. Methods of Use
Use jquery's JS file in a page that requires jquery.
Example: <script type= "Text/javascript" src= "Js/jquery.js" ></script>
After introduction, you can use the syntax provided by jquery anywhere on the page.

Iii. Learning Tutorials and reference materials
Please refer to the jquery Chinese API manual and Http://jquery.org.cn/visual/cn/index.xml
Recommended two good jquery tutorials: The beginning of jquery tutorial and the use of jquery to simplify Ajax development
(Note: The above documents are placed in the "accessories")

Iv. Grammar Summary and Precautions

1. References to page elements
The $ () reference element through jquery includes methods such as the ID, class, element name, and the hierarchy of elements and Dom or XPath conditions, and the returned object is a JQuery object (collection Object) and cannot be called directly by the DOM-defined method.

2. The conversion of JQuery objects to DOM objects
Only jquery objects can use the method defined by jquery. Note that DOM objects are different from jquery objects, and you should be aware of whether you are manipulating DOM objects or jquery objects when calling methods.
Ordinary DOM objects can generally be converted to jquery objects by $ ().
such as: $ (document.getElementById ("MSG")) is a jquery object, you can use the method of jquery.
Because the jquery object itself is a collection. So if a jquery object is to be converted to a DOM object, it must take one of these items, which is generally available through the index.
such as: $ ("#msg") [0],$ ("div"). EQ (1) [0],$ ("div"). get () [1],$ ("TD") [5] These are DOM objects, you can use the methods in the DOM, but you can't use the jquery method.
The following are the correct ways to do this:
$ ("#msg"). html ();
$ ("#msg") [0].innerhtml;
$ ("#msg"). EQ (0) [0].innerhtml;
$ ("#msg"). Get (0). InnerHTML;

3. How to get an item of the jquery collection
For a collection of captured elements, getting one of these items (specified by index) can be obtained using the EQ or get (n) method or index number, note that the EQ returns the JQuery object, and the Get (n) and the index return the DOM element object. jquery can only be used for jquery objects, whereas DOM objects can only use DOM methods, such as to get the contents of a third < div> element. There are two ways to do this:
$ ("div"). EQ (2). html (); Methods for invoking jquery objects
$ ("div"). Get (2). InnerHTML; Invoking the Dom's method properties

4. The same function implements set and get
Many of the methods in jquery are the same, mainly including the following:
$ ("#msg"). html (); Returns the HTML content of an element node with an ID of MSG.
$ ("#msg"). HTML ("<b>new content</b>");
Writes "<b>new content</b>" as an HTML string to the element node content with ID msg, and the page displays a bold new content

$ ("#msg"). Text (); Returns the text content of an element node with an ID of MSG.
$ ("#msg"). Text ("<b>new content</b>");
Writes "<b>new content</b>" as a plain text string in the element node content with ID msg, and the page displays a bold <b>new content</b>

$ ("#msg"). Height (); Returns the height of an element with an ID of MSG
$ ("#msg"). Height ("300"); Set the height of the element with ID msg to 300
$ ("#msg"). width (); Returns the width of an element with an ID of MSG
$ ("#msg"). Width ("300"); Set the width of the element with ID msg to 300

$ ("input"). Val ("); Returns the value of the form input box
$ ("input"). Val ("Test"); Set the value of the form input box to test

$ ("#msg"). Click (); Trigger Click event for an element with ID msg
$ ("#msg"). Click (FN); Add function for element with ID MSG Click event
The same Blur,focus,select,submit event can have two methods of invocation

5. Set Processing function
For the collection content returned by jquery without our own loop traversal and processing of each object individually, jquery has provided a convenient way for us to handle the collection.
There are two different forms:
$ ("P"). each (function (i) {this.style.color=[' #f00 ', ' #0f0 ', ' #00f ']})
Sets a different font color for the P elements indexed by 0,1,2 respectively.

$ ("tr"). each (function (i) {this.style.backgroundcolor=[' #ccc ', ' #fff '][i%2]})
To implement a table's interlaced color change effect

$ ("P"). Click (function () {alert (this). html ())})
A click event is added for each P element, and a P element pops up its contents

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;}
}); Expanded the Min,max two methods for jquery
To use the extended method (called by the "$. Method Name"):
Alert ("a=10,b=20,max=" +$.max (10,20) + ", min=" +$.min (10,20));

7. Ligatures of support methods
The so-called ligatures, that is, a jquery object can be continuously called a variety of different methods.
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
The main methods include the following:
$ ("#msg"). CSS ("background"); Returns the background color of an element
$ ("#msg"). CSS ("Background", "#ccc")//Set element background is gray
$ ("#msg"). Height (300); $ ("#msg"). Width ("200"); Set width height
$ ("#msg"). CSS ({color: "Red", Background: "Blue"});//Set style in the form of a name value pair
$ ("#msg"). AddClass ("select"); Adds a class with the name select for the element
$ ("#msg"). Removeclass ("select"); Remove the class with the element name of select
$ ("#msg"). Toggleclass ("select"); Delete (Add) class with Name Select if present (not present)

9. Perfect Event Handling function
jquery has provided us with a variety of event handling methods, and we do not need to write events directly on HTML elements, but we can add events directly to the objects acquired through jquery.
Such as:
$ ("#msg"). Click (function () {alert ("good")})//Add an clicked event for the element
$ ("P"). Click (function (i) {this.style.color=[' #f00 ', ' #0f0 ', ' #00f ']})
Set different processing for three different P-element click events, respectively
A few custom events in jquery:
(1) Hover (FN1,FN2): A method that mimics the hover event (moving the mouse over an object and moving out of the object). The first function that is specified is triggered when the mouse moves over a matching element. When the mouse moves out of this element, the specified second function is triggered.
When the mouse is placed on a row of the table, the class is set to over, leaving the time to be out.
$ ("tr"). Hover (function () {
$ (this). addclass ("over");
},
function () {
$ (this). AddClass ("Out");
});
(2) Ready (FN): Binds a function to execute when DOM loading is available for querying and manipulating.
$ (document). Ready (function () {alert ("Load Success")})
The page loads and prompts "load Success", which is equivalent to the OnLoad event. Equivalent to $ (FN)
(3) Toggle (EVENFN,ODDFN): Toggles the function to be called each time it is clicked. If a matching element is clicked, the first specified function is triggered, and when the same element is clicked again, the specified second function is triggered. Each subsequent click repeats the call to the two functions.
Rotate each Click to add and remove class named selected.
$ ("P"). Toggle (function () {
$ (this). AddClass ("selected");
},function () {
$ (this). Removeclass ("selected");
});
(4) Trigger (EventType): Triggers a class of events on each matched element.
For example:
$ ("P"). Trigger ("click"); Trigger Click event for all P elements
(5) Bind (EVENTTYPE,FN), Unbind (EventType): Event bindings and binding
Removes the bound event from each matching element (added).
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. Several practical effect functions
where the toggle () and Slidetoggle () methods provide state switching functionality.
such as 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: detects browser type. Valid parameters: Safari, Opera, MSIE, Mozilla. If the detection is Ie:$.browser.isie, ie browser returns TRUE.
$.each (obj, fn): A general-purpose iterative function. Can be used to iterate objects and arrays approximately (instead of loops).
Such as
$.each ([0,1,2], function (i, N) {alert ("Item #" + i + ":" + N);});
Equivalent to:
var temparr=[0,1,2];
for (Var i=0;i<temparr.length;i++) {
Alert ("Item #" +i+ ":" +temparr);
}
You can also work with JSON data, such as
$.each ({name: "John", Lang: "JS"}, function (i, N) {alert ("Name:" + i + ", Value:" + N);});
The result is:
Name:name, Value:john
Name:lang, Value:js
$.extend (TARGET,PROP1,PROPN): Extends an object with one or more other objects, returning the extended object. This is how the jquery implementation inherits.
Such as:
$.extend (settings, options);
Merge settings and options, and return the merge results to settings, equivalent to the options inheritance setting and save the inherited results in setting.
var settings = $.extend ({}, defaults, options);
Merges defaults and options, and returns the merge results to setting without overwriting the default content.
can have multiple parameters (merge multiple items and return)
$.map (Array, fn): array mapping. Saves an item in an array (after processing the transform) to another new array, and returns the resulting new array.
Such as:
var temparr=$.map ([0,1,2], function (i) {return i + 4;});
Temparr content is: [4,5,6]
var temparr=$.map ([0,1,2], function (i) {return i > 0? i + 1:null;});
Temparr content is: [2,3]
$.merge (ARR1,ARR2): Merges two arrays and removes duplicate items.
such as: $.merge ([0,1,2], [2,3,4])//return [0,1,2,3,4]
$.trim (str): Removes whitespace characters at both ends of a string.
such as: $.trim ("Hello, how is You?"); Back to "Hello,how is you?" "

12. Resolving conflicts between custom methods or other class libraries and jquery
Many times we have defined the $ (ID) method to get an element, or some other JS class library such as prototype also defined the $ method, if you put together these elements will cause variable method definition conflict, jquery specifically provides a way to solve this problem.
Use the Jquery.noconflict () method in jquery to pass control of the variable $ to the first library that implements it or to the previously customized $ method. Then when applying jquery, just replace all of the $ with jquery, such as the original Reference object method $ ("#msg") to jquery ("#msg").
Such as:
Jquery.noconflict ();
Get started with jquery
JQuery ("div p"). Hide ();
Use $ () for other libraries

$ ("content"). Style.display = ' None ';

A summary of tips for using jquery

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.