The features and basic usage of jquery developed by H5

Source: Internet
Author: User
Tags arrays bind extend min trim xpath

jquery is a fast, concise JavaScript framework, and jquery is popular, thanks in large part to its events with good semantics, excellent compatibility, and ease of management and expansion. With the rapid development and dissemination of WEB2.0 and Ajax ideas in the Internet, there have been some excellent JS frames, among which the prototype, YUI, JQuery, MooTools, Bindows and the JSVM framework of the country are more famous. jquery is another excellent JavaScript framework following prototype. It was created by John Resig in early 2006 to help simplify JavaScript and AJAX programming. jquery has 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, as well as basic XPath;
4. jquery is cross-browser and it supports browsers including IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+;
5. jquery can easily extend other functions for jquery;
6. The JS code and HTML code can be completely separated, easy to code and maintenance and modification;
7. Plugin rich, in addition to the jquery itself with some of the special effects, you can achieve more features through the plug-in, such as Form validation, tab navigation, drag and drop effects, table sorting, DataGrid, tree menu, image effects and Ajax uploads.
In the use of the same method as prototype, in the need to use jquery pages to introduce jquery js file.
For example: <script type= "Text/javascript" src= "Js/jquery.js" ></script> after introduction, you can use the syntax provided by jquery anywhere on the page.
1. References to page elements
The $ () reference element through jquery includes the hierarchy of the element by ID, class, element name, and Dom or XPath conditions, etc.
method, and the object returned is a JQuery object (collection Object), and the method defined by the DOM cannot be called directly.
Such as:
$ ("#msg"). html ();--> by id $ ("div"). html (); $ ("input"). Val (); --By the element name (jquery gets a collection) $ ("div p");  --The first line of code gets all the <p> elements under the <div> tab. $ ("Div.container")--the second line of code gets the <div> element $ ("div #msg") of class container;  --The third line of code gets the element with the ID msg below the <div> tag. $ ("Table A", context); --and the fourth line of code gets all the connection elements in the context table.

$ ("input[name= ' abc ')";--> gets the element named ABC.
2. The mutual conversion between jquery object and Dom object
2.1 Only jquery objects can use the method defined by jquery. Note that the DOM object and the jquery object are different, and the normal DOM
It is generally possible to convert from $ () to a jquery object.
such as: $ (document.getElementById ("MSG")) is a jquery object, you can use the method of jquery.

2.2 Because the JQuery object itself is a collection. So if the jquery object is to be converted to a DOM object, you must remove one of the items.
Can generally be removed by 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;

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.
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

3. 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 <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


$ ("#input_id"). attr ("name");//Gets the value of the property name


$ ("img"). attr ("src", "test.jpg");//Set the value of the IMG attribute src

The same Blur,focus,select,submit event can have both methods of invocation


4. Several useful jquery methods:
0) Collection 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 '][i]})
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]})


$ ("Li a"). each (function () {
if ($ (this). attr ("class") = = "Current") {
$ (this). Removeclass ("current");
}
if ($ (this). attr ("href") = = "{$sextype. URL}") {
$ (this). AddClass ("current");
}
});
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


1) $.browser. Browser type: detects browser type. Valid parameters: Safari, Opera, MSIE, Mozilla. If detection is
No Ie:$.browser.isie, IE browser returns TRUE.


2) $.each (obj, fn): The general iteration 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[i]);
}
3) You can also process 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


4) $.map (array, fn): array mapping. Saves an item in an array (after processing the transform) to another new array and returns
The new array to be generated back.
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]


5) $.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]

6) $.trim (str): Removes whitespace characters at both ends of the string.
Such as:

$.trim ("Hello, how is You?"); Back to "Hello,how is you?" "

5. 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)

6. 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 directly
Over jquery gets the object to add an event.
Such as

$ ("#msg"). Click (function () {alert ("good")})//Add an clicked event for the element
$ ("P"). Click (function (i) {this.style.color=[' #f00 ', ' #0f0 ', ' #00f '][i]})//for three different p

Element Click event to set different processing separately
A few custom events in jquery:
(1) Hover (FN1,FN2): When the mouse moves over a matching element, the first specified function is triggered. When the mouse moves
When this element is out, the second function that is specified 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")})
Page loading complete prompt "Load Success", different from onload event, onload requires page content loading complete (picture etc
), and ready is triggered whenever the page HTML code is downloaded. 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 trigger
Specifies the first function that fires the specified second function when the same element is clicked again. Each subsequent click repeats the
These two functions are called in turns.

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


7, 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));

8. Fade in and out

$ ("#msg"). FadeIn ("fast");
$ ("#msg"). FadeOut ("slow");

Yes, the above two lines of code have implemented a jquery object with ID msg to fade in and fade out. Make a dynamic loading notification bar like Gmail, which is as simple as jquery. Two functions accept the parameters in addition to the speed and so on, you can also receive integer, as the fade in or fade out of the completion time, in units of Ms.

9.plugin This is also a plug-in ERA.
The jquery plugin gives me the feeling of exclusively clean and simple. As Jtip, to use its function, simply add jtip to the class of your element and introduce Jtip.js and its style. Other things plug-in all-inclusive. One of the important reasons I like jquery is to find that she has a lot of good, wonderful plugins.


10. 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 change all of the $ into 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 ';

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.