Summary of jquery usage

Source: Internet
Author: User
Tags jquery library

--the notes are collated and quoted from the "http://www.cnblogs.com/Chenfengtao/archive/2012/01/12/2320490.html", thanks to the Bo Master's finishing! --

About jquery

jquery is a JavaScript function library, essentially a package for JS, which can be more convenient to use. For example JS to take the object document.getElementById () but with jquery words $ ("#id") can be. Using jquery, you can:

1. Quick access to document elements
jquery's selection mechanism is built on the CSS selector, which provides the ability to quickly query the elements in a DOM document, and greatly reinforces the way in which page elements are fetched in JavaScript.
2. Provide beautiful page dynamic effect
jquery has a series of animated effects that can develop very beautiful web pages, many of which use the built-in effects of jquery, such as fade-in, element-remove, and other dynamic effects.
3. Create Ajax No Refresh page
Ajax is an asynchronous JavaScript and ML abbreviation, can develop a very sensitive and non-refreshed web pages, especially when developing server-side web pages, such as PHP site, need to communicate with the server, if not using AJAX, each time the data updates have to re-refresh the page, and the use of Ajax effects , you can perform a local refresh of the page to provide a dynamic effect.
4. Provides enhancements to the JavaScript language
jquery provides enhancements to the basic JavaScript structure, such as element iterations and array manipulation.
5. Enhanced Event handling
jquery provides a variety of page events that prevent programmers from adding too much event handling code to HTML, and most importantly, its event handlers eliminate various browser compatibility issues.
6. Change the content of the webpage
jquery can modify the contents of a Web page, such as changing the text of a Web page, inserting or flipping a Web page image, and jquery simplifies the way in which JavaScript code would otherwise need to be processed.

Pre-preparation

Download the jquery library from the website and paste it into the project. (jQuery2.0 and subsequent versions will no longer support IE6/7/8 browser)

jquery use

The first thing to do is introduce jquery, which is actually introducing JavaScript. (from the HTML file's parent directory, find the jquery library under the JS file)

<type= "Text/javascript"  src= ": /js/jquery-1.11.0.js "></script>
1. Find the DOM node from the Web document
$ (document)//Select entire Document Object$ (' #myId ')//Select a page element with ID myID$ (' Div.myclass ')//Select a DIV element with class MyClass$ (' input[name=first] ')//Select the INPUT element with the Name property equal to first$ (' A:first ')//Select the first a element in a Web page$ (' tr:odd ')//select odd rows of a table$ (' #myForm: Input ')//Select the INPUT element in the form$ (' div:visible ')//Select a visible div element$ (' Div:gt (2) ')//Select all DIV elements except the first three$ (' div:animated ')//Select the div element that is currently in the animation state
2. Change the result set

If multiple elements are selected, jquery provides filters to narrow the result set:

$ (' div '). has (' P ');  // Select the div element  that contains the P element $ (' div '). Not ('. MyClass ');  // Select a DIV element  that is not equal to the MyClass class $ (' div '). Filter ('. MyClass ');  // Select a DIV element  with class equal to MyClass $ (' div '). First ();  // Select a 1th div element   $ (' div '). EQ (5);  // Select a 6th div element  

Sometimes we need to move from the result set to nearby related elements, and jquery also provides a way to move around the DOM tree:

$ (' div '). Next (' P ');  // Select the first P element  after a DIV element $ (' div '). parent ();  // Select the parent element  of the DIV element $ (' div '). Closest (' form ');  // Select the form parent element  closest to Div $ (' div '). Children ();  // Select all child elements  of Div $ (' div '). siblings ();  // Select sibling elements  of Div
3. Chain-Operated

When you select a page element, you can do something about it.
jquery allows all operations to be linked together and written in the form of chains, such as:

$ (' div '). Find (' H3 '). EQ (2). html (' Hello ');

This can be unpacked:

$ (' div ')  // Find div element   . Find (' H3 ')  // Select the H3 element  in it. EQ (2)    Select the 3rd h3 element   . html (' Hello ');  // change its contents to Hello  

Its principle is that each step of the jquery operation, the return is a jquery object, so the different operations can be linked together.
jquery also provides the . End () method, which allows the result set to step back:

$ (' div ').  Find (' H3 ').  eq (2).  html (' Hello ')  . End ()     go back to the step  that selects all the H3 elements . EQ (0)  // Select the first H3 element   . HTML (' World ');  // change  its contents to the world
4. Value and assignment of elements

jquery uses the same function to complete the value (getter) and assignment (setter). Whether it is a value or an assignment is determined by the parameters of the function.

$ (' H1 '). html ();  //  $ (' H1 '). html (' Hello ');  // HTML () has parameter Hello, which means to assign a value  to the H1 // the common values and assignment functions are as follows: . HTML ()  . Text ()  // Remove or set text contents   . attr ()  //  Remove or set the  value of a property . Width ()  // Remove or set the width  of an element . Height ()  // removes or sets the height  of an element . Val ()  // Remove or set HTML content to take out the value  of a FORM element

Note: If the result set contains more than one element, all of the elements will be assigned a value when assigned;
When the value is taken, it is only the value of the first element (. Text () exception, which takes out the text content of all elements).

5. Manipulation of elements: moving

If you want to move the selected element, there are two methods: one is to move the element directly, and the other is to move the other elements so that the target element reaches the position we want.
Suppose we select a DIV element and we need to move it behind the P element.

The first method is to use the . InsertAfter ()to move the DIV element behind the P element:

$ (' div '). InsertAfter (' P ');

The second method is to use. After (), add the P element to the front of the DIV element:

$ (' P '). After (' div ');

The difference between the two methods is that the elements returned are not the same. The first method returns the DIV element, and the second method returns the P element. Make your choice as needed. There are four groups of the same:

. InsertAfter () and. After ()  // outside of existing elements, insert elements  from behind . InsertBefore () and. Before ()  // from the outside of the existing element, insert the  element from the front . AppendTo () and. Append ()  // inside the existing element, insert the element  from behind . Prependto () and. Prepend ()  //  inside the existing element, insert the element from the front
6. Operation of elements: copying, deleting, and creating

The copy element uses . Clone ().

The delete element uses . Remove () and . Detach (). The difference between the two is that the former does not retain the event of the deleted element, which is reserved for use when re-inserting the document.

Empty the element content (but not delete the element) using . Empty ().

The way to create a new element is as simple as passing the new element directly into the jquery constructor:

$ (' <p>Hello</p> ');  $ (' <li class= "new" >new list item</li> ');  $ (' ul '). Append (' <li>list item</li> ');  
7. Tool methods

In addition to manipulating the selected elements, jquery provides some tool methods (utility) that you can use directly without having to select the elements.
It is essentially the method defined on the jquery constructor, the Jquery.method (), just like the native function of JavaScript, so it can be used directly. The methods that manipulate elements are those that define the prototype object on the constructor, that is, JQuery.prototype.method (), so you must generate an instance (that is, select the element) to use.

Common tool methods are as follows:

$.trim ()//removes spaces at both ends of the string. $.each ()//iterates over an array or an object. $.inarray ()//returns the index position of a value in the array.  Returns 1 if the value is not in the array. $.grep ()//returns an element in an array that conforms to a standard. $.extend ()//merges multiple objects into the first object. $.makearray ()//Converts an object to an array. $.type ()//determine the category of the object (function object, Date object, array object, regular object, and so on). $.isarray ()//determines whether a parameter is an array. $.isemptyobject ()//determines whether an object is empty (does not contain any attributes). $.isfunction ()//determines whether a parameter is a function. $.isplainobject ()//determines whether a parameter is an object created with "{}" or "New object". $.support ()//Determines whether a feature is supported by the browser. 
8. Practical operation

jquery can bind events to page elements. Depending on the event, run the appropriate function.

$ (' P '). Click (function () {  alert (' Hello ');  });

Currently, jquery supports the following events mainly:

. Blur ()//The form element loses focus. . Change ()//the value of the form element is changed. Click ()//Mouse click. DblClick ()//Mouse Double-click. Focus ()//form elements Get focus. Focusin ()//child elements Get focus. Focusout ()//child element loses focus. Hover ()//specifying handler functions for both MouseEnter and MouseLeave events. KeyDown ()//Press the keyboard (long-time key to return only one event). KeyPress ()//Press the keyboard (long-time keys will return multiple events). KeyUp ()//Loosen the keyboard. Load ()//element Loading complete. MouseDown ()//Press the mouse. MouseEnter ()//Mouse entry (Enter child element does not trigger). MouseLeave ()//Mouse away (leave child element not triggered). MouseMove ()//mouse moves inside the element. Mouseout ()//Mouse off (leave child element also triggered). MouseOver ()//Mouse entry (Enter child element also trigger). MouseUp ()//Release Mouse. Ready ()//Dom loading complete. Resize ()//the size of the browser window has changed. Scroll ()//the position of the scroll bar is changed. Select ()//the user selects the contents of the text box. Submit ()//user submits the form. Toggle ()//run multiple functions in sequence based on the number of mouse clicks. Unload ()//The user leaves the page

These events are a handy way of . Bind () inside jquery. Using. Bind () gives you more flexibility in controlling events, such as binding the same function for multiple events

$ (' input '). Bind (  // bind both click and Change event   function () {  alert (' Hello ');  }  );

If you only want the event to run once, you can use the . One () method.

$ ("P"). One ("click", Function () {  alert ("Hello");  // run only once, subsequent clicks will not run   });

  . Unbind () is used to unbind events.

$ (' P '). Unbind (' click ');

All event handlers can accept an event object as an argument, such as E in the following example:

$ ("P"). Click (function (e) {      //"click"  });

This event object has some useful properties and methods:

Event.pagex  / / event occurs when the mouse is at a horizontal distance from the upper left corner of the page event.pagey  //event.type  // the type of event (for example, click)event.which  // Press which key event.data  //  Bind the data on the event object, and then pass in the event handler function event.target  // Event-oriented page element Event.preventdefault ()  // the default behavior of blocking events (such as clicking on a link that automatically opens a new page)event.stoppropagation ()  // stop event bubbles to the upper element

In the event handler, you can use the This keyword to return the DOM element that the event targets:

$ (' a '). Click (function () {      if ($ (this). attr (' href '). Match (' evil ')) {  //  If it is identified as  a harmful link        e.preventdefault ();  // Block Open          $ (this). addclass (' evil ');  // plus the class  that represents the harmful     }  });    

There are two ways to automatically trigger an event. One is to use the event function directly, and the other is to use . Trigger () or . Triggerhandler ().

$ (' a '). Click (); $ (' a '). Trigger (' click ');
9. Special effects

jquery allows objects to render some special effects.

$ (' H1 '). Show ();  // show a H1 title

The usual special effects are as follows:

. FadeIn ()  // fade in. FadeOut ()  // fade out. FadeTo ()/  / Adjust Transparency . Hide ()  // Hide Element . Show ()  // display element . Slidedown ()  // expand Down . Slideup ()  // roll up . Slidetoggle ()  // expand or roll up an element in turn . Toggle ()  // Show or hide an element in turn

Except for . Show () and . Hide (), the default execution time for all other effects is 400ms (milliseconds), but you can change this setting.

$ (' H1 '). FadeIn (+);  // fade  in 300 milliseconds $ (' H1 '). FadeOut (' slow ');  // slowly fade out

After the effect finishes, you can specify that a function be executed.

$ (' P '). FadeOut, function () {    $ (this). Remove ();});

More complex effects can be customized with . Animate () .

$ (' div '). Animate (  {  "+=50",  // move  right opacity:0.25   //  Specify transparency   },+,  //  duration   function () {     alert (' Done! ');  // callback function });

. Stop () and. Delay () are used to stop or delay the execution of the effect. $.fx.off if set to true, all page effects are turned off.

Summary of jquery usage

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.